<?php

namespace app\api\controller;

use app\api\model\Block;
use app\api\model\Papers;
use app\api\model\Task;
use app\common\controller\Api;
use app\common\library\Image;
use think\Db;
use Exception;
use fast\Random;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\exception\PDOException;


/**
 * 考试
 */
class Exams extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    // protected $noNeedLogin = ['examType', 'examRange', 'examMarkPattern', 'examQuestionType', 'setExamListStatus', 'getExamPaperImageInfo', 'examInfo', 'setUnusual','setTotalScore'];
    // 无需鉴权的接口,*表示全部
    // protected $noNeedRight = ['examType', 'examRange', 'examMarkPattern', 'examQuestionType', 'setExamListStatus', 'getExamPaperImageInfo','zgAnswerList'];
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $importHeadType = 'comment';
    protected $blockType = ['alone' => '单评', 'dual' => '双评'];
    protected $allotType = [0 => '未设置', 1 => '平均分配', 2 => '效率优先', 3 => '定量分配'];
    protected $statusType = [0 => '待阅', 1 => '阅卷中', 2 => '已完成', 3 => '暂停中'];
    protected $basepath = "/www/wwwroot/admin.xchengguang.com/runzhi-grading/public";
    //考试类型
    public function examType()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $list = db('exam_type')->where(['status' => 'normal'])->field('id,name')->order('weigh asc')->select();
        $this->success('考试类型', $list);
    }

    //考试范围
    public function examRange()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $list = db('exam_range')->where(['status' => 'normal'])->field('id,name')->order('weigh asc')->select();
        $this->success('考试范围', $list);
    }

    //阅卷模式
    public function examMarkPattern()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $list = db('exam_mark_pattern')->where(['status' => 'normal'])->field('id,name')->order('weigh asc')->select();
        $this->success('考试范围', $list);
    }

    //添加科目
    public function addSubject()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $name = $this->request->post('name');
        if (!$name)
            $this->error('未知参数！');
        $in = db('subject')->insert([
            'type' => 1,
            'name' => $name,
            'create_time' => time()
        ]);
        if (!$in)
            $this->error('操作失败');
        $list = db('subject')->field('id,name')->order('create_time desc')->select();
        $this->success('操作成功', $list);
    }


    //添加考试
    public function addExam()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $param = $this->request->post();
        if (!$param)
            $this->error('未知参数！');
        if (!isset($param['range_id']) || !$param['range_id'])
            $this->error('请选择考试范围!');
        if (!isset($param['name']) || !$param['name'])
            $this->error('请填写考试名称!');
        if (!isset($param['starttime']) || !$param['starttime'])
            $this->error('请选择考试开始时间!');
        $param['starttime'] = strtotime($param['starttime']);
        if (!isset($param['endtime']) || !$param['endtime'])
            $this->error('请选择考试结束时间!');
        $param['endtime'] = strtotime($param['endtime']);
        if (!isset($param['type_id']) || !$param['type_id'])
            $this->error('请选择考试类型时间!');
        if (!isset($param['pattern_id']) || !$param['pattern_id'])
            $this->error('请选择阅卷模式!');
        if (!isset($param['grade_id']) || !$param['grade_id'])
            $this->error('请选择年级!');
        // if (!isset($param['class_ids']) || !$param['class_ids']) $this->error('请选择班级!');
        if (!isset($param['subject_ids']) || !$param['subject_ids'])
            $this->error('请选择考试科目!');
        if (!isset($param['school_ids']) || !$param['school_ids']) {
            $param['school_ids'] = $this->school_id;
        }

        $param['user_id'] = $this->user_id;
        $param['createtime'] = time();
        $param['grade_name'] = db('grade')->where(['id' => $param['range_id']])->value('name');
        $result = false;

        Db::startTrans();
        try {
            $in = db('exams')->insertGetId($param);
            if (!$in)
                throw new Exception("添加失败！");
            $child = [];
            $subjectarr = explode(',', $param['subject_ids']);
            foreach ($subjectarr as $key => $value) {
                $child[$key]['user_id'] = $param['user_id'];
                $child[$key]['exams_id'] = $in;
                $child[$key]['subject_id'] = $value;
                $child[$key]['name'] = db('subject')->where(['id' => $value])->value('name');
                if ($param['class_ids']) {
                    $class_ids = explode(',', $param['class_ids']);
                    $child[$key]['studentnum'] = db('student')->where(['grade_id' => $param['grade_id'], 'school_id' => $this->school_id])->where('class_id', 'in', $class_ids)->count();
                } else {
                    $child[$key]['studentnum'] = db('student')->where(['grade_id' => $param['grade_id'], 'school_id' => $this->school_id])->count();
                }

                $child[$key]['createtime'] = time();
            }
            $childin = db('exam_list')->insertAll($child);
            if (!$childin)
                throw new Exception("添加失败！");
            $result = true;
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加成功！');
        } else {
            $this->error('添加失败！');
        }
    }

    //增加科目
    public function editExam()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        $subject_ids = $this->request->post('subject_ids');
        if (!$id || !$subject_ids)
            $this->error('未知参数！');
        $exam = db('exams')->where(['id' => $id])->find();
        if (!$exam)
            $this->error('未找到相关考试信息！');

        //已有科目
        $subjectIds = explode(',', $exam['subject_ids']);
        $newSubjectIds = explode(',', $subject_ids);
        $child = [];
        foreach ($newSubjectIds as $key => $value) {
            if (!in_array($value, $subjectIds)) {
                $child[$key]['user_id'] = $exam['user_id'];
                $child[$key]['exams_id'] = $id;
                $child[$key]['subject_id'] = $value;
                $child[$key]['name'] = db('subject')->where(['id' => $value])->value('name');
                $child[$key]['studentnum'] = db('student')->where(['grade_id' => $exam['grade_id'], 'school_id' => $this->school_id])->where('class_id', 'in', $exam['class_ids'])->count();
                $child[$key]['createtime'] = time();
            }
        }
        $childin = db('exam_list')->insertAll($child);
        if (!$childin)
            $this->error("增加失败！");
        db('exams')->where(['id' => $id])->update(['subject_ids' => $subject_ids]);
        $this->success('增加成功！');
    }

    //考试详情
    public function examDetail()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id)
            $this->error('未知参数！');
        $exam = db('exams')->where(['id' => $id])->find();
        if (!$exam)
            $this->error('未找到相关考试信息！');
        $exam['list'] = db('exam_list')->where(['exams_id' => $exam['id']])->select();
        $this->success('考试详情', $exam);
    }

    //考试列表
    public function examList()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $school_id = $this->school_id;
        $page = $this->request->post('page');
        $pagesize = $this->request->post('pagesize');
        if (!$page || !$pagesize)
            $this->error('未知参数！');
        $grade_id = $this->request->post('grade_id');
        $month = $this->request->post('month');
        $range_id = $this->request->post('range_id');
        $name = $this->request->post('name');

        $where = ['school_ids' => $school_id];
        $list = db('exams')
            ->where(function ($query) use ($grade_id) {
                if ($grade_id) {
                    $query->where('grade_id', $grade_id);
                }
            })
            ->where(function ($query) use ($month) {
                if ($month) {
                    $time = date('Y-m', strtotime($month));
                    $query->where('FROM_UNIXTIME(createtime,"%Y-%m")="' . $time . '"');
                }
            })
            ->where(function ($query) use ($range_id) {
                if ($range_id) {
                    $query->where('range_id', $range_id);
                }
            })
            ->where(function ($query) use ($name) {
                if ($name) {
                    // $grade_ids = db('student')->where('name', 'like', '%' . $studentname . '%')->column('id');
                    // $query->where('grade_id', 'in', $grade_ids);
                    $query->where('name', 'like', '%' . $name . '%');
                }
            })
            ->where($where)
            ->order('createtime desc')->paginate($pagesize, false)->each(function ($item, $index) {
                $item['type_name'] = db('exam_type')->where(['id' => $item['type_id']])->value('name');
                $item['range_name'] = db('exam_range')->where(['id' => $item['range_id']])->value('name');
                $item['pattern_name'] = db('exam_mark_pattern')->where(['id' => $item['pattern_id']])->value('name');
                //创建人
                $item['username'] = db('user')->where(['id' => $item['user_id']])->value('nickname');
                $item['examtime'] = date('Y-m-d', $item['starttime']) . ' - ' . date('Y-m-d', $item['endtime']);
                $item['starttime'] = date('Y-m-d', $item['starttime']);
                $item['endtime'] = date('Y-m-d', $item['endtime']);
                $list = db('exam_list')->where(['exams_id' => $item['id']])->select();
                foreach ($list as $key => &$value) {
                    //题块数量
                    $block = db('exam_paper_block')->where(['exams_list_id' => $value['id']])->field('id')->select();
                    $blockNum = count($block);
                    //学生数
                    $studentNum = db('exam_paper_images')->where(['exams_list_id' => $value['id']])->group('key')->count();
                    $value['scannum'] = $studentNum;
                    $makeNum = 0;
                    foreach ($block as $val) {
                        //已评卷数
                        $maNum = db('exam_teacher_make_log')->where(['exams_list_id' => $value['id'], 'block_id' => $val['id']])->field('student_id')->group('student_id')->count();
                        $makeNum = bcadd($makeNum, $maNum, 0);
                    }

                    //阅卷进度
                    $value['marknum'] = 0;
                    if ($studentNum > 0) {
                        $value['marknum'] = round(($makeNum / ($studentNum * $blockNum)) * 100, 3);
                    }
                }
                $item['list'] = $list;
                return $item;
            });
        $this->success('考试列表', $list);
    }

    //删除考试
    public function delExam()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id)
            $this->error('未知参数');

        $del = db('exams')->where('id', $id)->delete();
        if ($del) {

            db('exam_list')->where(['exams_id' => $id])->delete();
            db('exam_images')->where(['exams_id' => $id])->delete();
            db('exam_paper_block')->where(['exams_id' => $id])->delete();
            db('exam_paper_images')->where(['exams_id' => $id])->delete();
            db('exam_paper_marking_area')->where(['exams_id' => $id])->delete();
            db('exam_paper_question')->where(['exams_id' => $id])->delete();
            db('exam_paper_question_answer')->where(['exams_id' => $id])->delete();
            db('exam_paper_question_list')->where(['exams_id' => $id])->delete();
            db('exam_paper_student')->where(['exams_id' => $id])->delete();
            db('exam_paper_student_list')->where(['exams_id' => $id])->delete();
            db('exam_teacher_make_log')->where(['exams_id' => $id])->delete();
            db('task')->where(['exams_id' => $id])->delete();
        }
        $this->success('操作成功');
    }

    //试题类型
    public function examQuestionType()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $type = $this->request->get('type');
        if (!in_array($type, ['KG', 'ZG']))
            $this->error('参数错误！');
        $list = db('exam_question_type')->where(['status' => 'normal', 'type' => $type])->field('id,name,key')->order('weigh asc')->select();
        $this->success('试题类型', $list);
    }

    //新增客观试题
    public function setPaperQuestion()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $school_id = $this->school_id ?? 1;
        $type = 'KG';
        $name = $this->request->post('name');
        $key = $this->request->post('key');
        $exams_list_id = $this->request->post('exams_list_id');
        $question_type = $this->request->post('question_type'); //客观题类型

        $optionnum = $this->request->post('optionnum'); //选项
        $score = $this->request->post('score'); //每题分数
        $qnumrange = $this->request->post('qnumrange'); //题号范围
        $louxuan_score = $this->request->post('louxuan_score'); //多选题漏选得分

        $questions = $this->request->param('questions/a');
        $formList = $this->request->param('formlist/a');
        if (!$name || !$key || !$exams_list_id || !$score)
            $this->error('未知参数！');
        if (!is_array($questions))
            $this->error('参数格式错误！');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        $checkexpaper = db('exam_paper_question')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'key' => $key])->find();
        if ($checkexpaper)
            $this->error('该大题题号已存在！');
        // //小题总数
        // $qnumrangearr = explode('-', $qnumrange);
        // $num = ($qnumrangearr[1] - $qnumrangearr[0]) + 1;
        //总分
        $zscore = $score; //$num * $score;

        $result = false;
        Db::startTrans();
        try {

            $in = db('exam_paper_question')->insertGetId([
                'exams_id' => $exams_id,
                'exams_list_id' => $exams_list_id,
                'name' => $name,
                'key' => $key,
                'question_type' => $question_type,
                'optionnum' => $optionnum,
                'type' => $type,
                'score' => $score,
                'zscore' => $zscore,
                'qnumrange' => $qnumrange,
                'louxuan_score' => $louxuan_score,
                'content' => json_encode($questions),
                'formlist' => json_encode($formList)
            ]);
            if (!$in)
                throw new Exception("操作失败！");

            foreach ($questions as &$value) {
                $value['exams_id'] = $exams_id;
                $value['exams_list_id'] = $exams_list_id;
                $value['question_id'] = $in;
                // 'question_type' => $question_type,
                $value['type'] = $type;
            }
            db('exam_paper_question_list')->insertAll($questions);
            $result = true;
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加成功！');
        } else {
            $this->error('添加失败！');
        }
    }

    //编辑客观试题
    public function savePaperQuestion()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $school_id = $this->school_id ?? 1;
        $type = 'KG';
        $id = $this->request->post('id');
        $name = $this->request->post('name');
        $key = $this->request->post('key');
        $exams_list_id = $this->request->post('exams_list_id');
        $question_type = $this->request->post('question_type'); //客观题类型

        $optionnum = $this->request->post('optionnum'); //选项
        $score = $this->request->post('score'); //每题分数
        $qnumrange = $this->request->post('qnumrange'); //题号范围
        $louxuan_score = $this->request->post('louxuan_score'); //多选题漏选得分
        $questions = $this->request->param('questions/a');
        $formList = $this->request->param('formlist/a');
        if (!$id)
            $this->error('参数错误！');
        if (!is_array($questions))
            $this->error('参数格式错误！');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        $paper = db('exam_paper_question')->where(['id' => $id])->find();
        if (!$paper)
            $this->error('未找到相关信息！');
        //小题总数
        // $qnumrangearr = explode('-', $qnumrange);
        // $num = ($qnumrangearr[1] - $qnumrangearr[0]) + 1;
        //总分
        $zscore = $score; //$num * $score;

        $result = false;
        Db::startTrans();
        try {
            
            $up = db('exam_paper_question')->where('id', $id)->update([
                'exams_id' => $exams_id,
                'exams_list_id' => $exams_list_id,
                'name' => $name,
                'key' => $key,
                'question_type' => $question_type,
                'optionnum' => $optionnum,
                'type' => $type,
                'score' => $score,
                'zscore' => $zscore,
                'qnumrange' => $qnumrange,
                'louxuan_score' => $louxuan_score,
                'content' => json_encode($questions),
                'formlist' => json_encode($formList)
            ]);
            db('exam_paper_question_list')->where(['question_id' => $id])->delete();
            $data = [];
            foreach ($questions as $key=>$value) {
                
                $data[$key] = [
                    'exams_id' => $exams_id,
                    'exams_list_id'=> $exams_list_id,
                    'question_id'=> $id,
                    'type'=> $type,
                    'name' => $value['name'],
                    'key'=> $value['key'],
                    'index'=> $value['index'],
                    'optionnum'=> $value['optionnum'],
                    'question_type'=> $value['question_type'],
                    'score'=> $value['score'],
                    'answer'=> $value['answer'],
                    'louxuan_score'=> $value['louxuan_score']
                ];
            }
            db('exam_paper_question_list')->insertAll($data);
            $result = true;
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //新增主观试题
    public function setPaperQuestionZhu()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $school_id = $this->school_id ?? 1;
        $type = 'ZG';
        $name = $this->request->post('name');
        $key = $this->request->post('key');
        $exams_list_id = $this->request->post('exams_list_id');
        $score = $this->request->post('score'); //每题分数
        $questions = $this->request->param('questions/a');
        $formList = $this->request->param('formlist/a');
        if (!$name || !$key || !$exams_list_id || !$score)
            $this->error('未知参数！');

        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        $checkexpaper = db('exam_paper_question')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'key' => $key])->find();
        if ($checkexpaper)
            $this->error('该大题题号已存在！');
        if ($questions) {
            if (!is_array($questions))
                $this->error('参数格式错误！');
        }
        //总分
        $zscore = $score;

        $result = false;
        Db::startTrans();
        try {

            $in = db('exam_paper_question')->insertGetId([
                'exams_id' => $exams_id,
                'exams_list_id' => $exams_list_id,
                'name' => $name,
                'key' => $key,
                'type' => $type,
                'score' => $score,
                'zscore' => $zscore,
                'content' => json_encode($questions),
                'formlist' => json_encode($formList)
            ]);
            if (!$in)
                throw new Exception("操作失败！");
            if ($questions) {
                foreach ($questions as &$value) {
                    $value['exams_id'] = $exams_id;
                    $value['exams_list_id'] = $exams_list_id;
                    $value['question_id'] = $in;
                    $value['type'] = $type;
                }
                db('exam_paper_question_list')->insertAll($questions);
            }

            $result = true;
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('添加成功！');
        } else {
            $this->error('添加失败！');
        }
    }

    //编辑主观试题
    public function savePaperQuestionZhu()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $school_id = $this->school_id ?? 1;
        $type = 'ZG';
        $id = $this->request->post('id');
        $name = $this->request->post('name');
        $key = $this->request->post('key');
        $exams_list_id = $this->request->post('exams_list_id');
        $score = $this->request->post('score'); //每题分数
        $questions = $this->request->param('questions/a');
        $formList = $this->request->param('formlist/a');
        if (!$id)
            $this->error('参数错误！');
        if (!is_array($questions))
            $this->error('参数格式错误！');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        $paper = db('exam_paper_question')->where(['id' => $id])->find();
        if (!$paper)
            $this->error('未找到相关信息！');
        $zscore = $score;
        $result = false;
        Db::startTrans();
        try {

            $up = db('exam_paper_question')->where('id', $id)->update([
                'exams_id' => $exams_id,
                'exams_list_id' => $exams_list_id,
                'name' => $name,
                'key' => $key,
                'type' => $type,
                'score' => $score,
                'zscore' => $zscore,
                'content' => json_encode($questions),
                'formlist' => json_encode($formList)
            ]);
            if ($questions) {
                db('exam_paper_question_list')->where(['question_id' => $id])->delete();
                $data = [];
                foreach ($questions as $key=>$value) {
                    
                    $data[$key] = [
                        'exams_id' => $exams_id,
                        'exams_list_id'=> $exams_list_id,
                        'question_id'=> $id,
                        'type'=> $type,
                        'name' => $value['name'],
                        'key'=> $value['key'],
                        'question_type'=> $value['question_type'],
                        'score'=> $value['score'],
                    ];
                }
                db('exam_paper_question_list')->insertAll($data);
            }
            $result = true;
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //删除试题
    public function delPaperQuestion()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $school_id = $this->school_id;
        $id = $this->request->post('id');
        if (!$id)
            $this->error('参数错误！');
        db('exam_paper_question')->where(['id' => $id])->delete();
        db('exam_paper_question_list')->where(['question_id' => $id])->delete();
        $this->success('操作成功！');
    }

    //试卷结构列表
    public function paperQuestionList()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->get('exams_list_id');
        $type = $this->request->get('type');
        if (!$exams_list_id)
            $this->error('参数错误！');
        if ($type) {
            $list = db('exam_paper_question')->where(['exams_list_id' => $exams_list_id, 'type' => $type])->select();
        } else {
            $list = db('exam_paper_question')->where(['exams_list_id' => $exams_list_id])->select();
        }

        foreach ($list as &$value) {
            $value['son'] = db('exam_paper_question_list')->where(['question_id' => $value['id']])->select();
        }
        $this->success('结构列表', $list);
    }

    //试卷详细列表
    public function paperQuestionDetail()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $id = $this->request->get('id');
        if (!$id)
            $this->error('参数错误！');
        $info = db('exam_paper_question')->where(['id' => $id])->find();
        if ($info) {
            $info['son'] = db('exam_paper_question_list')->where(['question_id' => $info['id']])->select();
        }
        $this->success('结构详情', $info);
    }

    //扫描机配置参数
    public function setScanConfig()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $param = $this->request->param('param/a');
        if (!$exams_list_id)
            $this->error('未知参数！');
        if (!is_array($param))
            $this->error('参数格式错误！');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');

        $result = false;
        Db::startTrans();
        try {
            $checkScan = db('exam_scan_config')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id])->find();
            if (!$checkScan) {
                $in = db('exam_scan_config')->insertGetId([
                    'exams_id' => $exams_id,
                    'exams_list_id' => $exams_list_id,
                    'param' => json_encode($param)
                ]);
                if (!$in)
                    throw new Exception("操作失败！");
                $result = true;
            } else {
                $in = db('exam_scan_config')->where('id', $checkScan['id'])->update([
                    'param' => json_encode($param)
                ]);
                $result = true;
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //扫描机配置参数
    public function getScanConfig()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $data = db('exam_scan_config')->where(['exams_list_id' => $exams_list_id])->find();
        if ($data) {
            $data['param'] = json_decode($data['param'], true);
        }
        $this->success('操作成功！', $data);
    }

    //考号区内容
    public function setPaperMarkingArea()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $school_id = $this->school_id ?? 1;
        $imgFileId = $this->request->post('imgFileId');
        $exams_list_id = $this->request->post('exams_list_id');
        $location = $this->request->param('location/a');
        $content = $this->request->param('content/a');
        $keguanti = $this->request->param('keguanti/a');
        if (!$exams_list_id)
            $this->error('未知参数！');
        if (!is_array($location) || !is_array($content) || !is_array($keguanti))
            $this->error('参数格式错误！');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        $checkPaper = db('exam_paper_marking_area')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id])->find();
        if ($checkPaper)
            db('exam_paper_marking_area')->where(['id' => $checkPaper['id']])->delete();
        $result = false;
        Db::startTrans();
        try {
            $in = db('exam_paper_marking_area')->insertGetId([
                'exams_id' => $exams_id,
                'exams_list_id' => $exams_list_id,
                'location' => json_encode($location),
                'content' => json_encode($content),
                'keguanti' => json_encode($keguanti),
                'imgFileId' => $imgFileId
            ]);
            if (!$in)
                throw new Exception("操作失败！");
            $result = true;
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            db('exam_list')->where('id', $exams_list_id)->update(['status' => 1]);
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //客观题设置答案页
    public function kgAnswerPage()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->get('exams_list_id'); //科目id
        if (!$exams_list_id)
            $this->error('未知参数！');
        $group = db('exam_paper_question_list')->where(['exams_list_id' => $exams_list_id, 'type' => 'KG'])->field('id,exams_list_id,question_type,question_id')->group('question_type')->order('question_id asc')->select();
        $data = [];
        foreach ($group as $key => $value) {
            // $questionName = db('exam_paper_question')->where(['id'=>$value['question_id']])->value('name');
            $typeName = db('exam_question_type')->where(['key' => $value['question_type']])->value('name');
            $list = db('exam_paper_question_list')->where(['exams_list_id' => $value['exams_list_id'], 'question_type' => $value['question_type']])->order('id asc')->select();
            foreach ($list as &$item) {
                $item['typename'] = db('exam_question_type')->where(['key' => $item['question_type']])->value('name');
            }
            $data[$key]['questionname'] = $typeName;
            $data[$key]['list'] = $list;
        }
        $this->success('客观题设置答案页', $data);
    }

    //客观题设置答案
    public function kgSetAnswer()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $content = $this->request->param('content/a');
        if (!is_array($content))
            $this->error('参数格式错误！');
        foreach ($content as $key => $value) {
            db('exam_paper_question_list')->where(['id' => $value['id'], 'type' => 'KG'])->update(['answer' => $value['answer']]);
        }
        $this->success('操作成功！');
    }

    //主观题答案列表
    public function zgAnswerList()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id)
            $this->error('参数错误！');
        $list = db('exam_paper_question_answer')->where(['exams_list_id' => $id])->column('images');
        foreach ($list as &$value) {
            $value = $value ? cdnurl($value, true) : '';
        }
        $this->success('主观题答案列表', $list);
    }

    //主观题设置答案
    public function zgSetAnswer()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        $images = $this->request->post('images');
        if (!$id || !$images)
            $this->error('参数错误！');
        $exam = db('exam_list')->where(['id' => $id])->find();
        if (!$exam)
            $this->error('单科错误！');
        $in = db('exam_paper_question_answer')->insert([
            'exams_id' => $exam['exams_id'],
            'exams_list_id' => $exam['id'],
            'images' => $images
        ]);
        if ($in) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //设置附加题
    public function changeQuestionType()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $content = $this->request->param('content/a');
        if (!is_array($content))
            $this->error('参数格式错误！');
        foreach ($content as $key => $value) {
            db('exam_paper_question_list')->where(['id' => $value['id'], 'type' => 'ZG'])->update(['question_type' => $value['question_type']]);
        }
        $this->success('操作成功！');
    }

    //主观题结构
    public function zgStructure()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->get('exams_list_id'); //科目id
        if (!$exams_list_id)
            $this->error('未知参数！');
        $list = db('exam_paper_question')->where(['exams_list_id' => $exams_list_id, 'type' => 'ZG'])->field('id,name,key,score')->select();
        foreach ($list as &$value) {
            $son = db('exam_paper_question_list')->where(['question_id' => $value['id'], 'type' => 'ZG'])->field('id,name,key,score,setblock')->select();
            $value['son'] = $son;
        }
        $this->success('主观题结构', $list);
    }


    //设置题块
    public function setExamPaperBlock()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id'); //科目id
        $data = $this->request->param('data/a'); //参数内容
        if (!$exams_list_id)
            $this->error('未知参数！');
        if (!is_array($data))
            $this->error('参数格式错误！');
        $exam = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exam)
            $this->error('单科错误！');
        $result = false;
        Db::startTrans();
        try {
            foreach ($data as $key => $value) {
                $score = 0;
                foreach ($value['params'] as $param) {
                    $score = bcadd($score, $param['score']);
                }
                db('exam_paper_block')->insert([
                    'name' => $value['name'],
                    'score' => $score,
                    'exams_id' => $exam['exams_id'],
                    'exams_list_id' => $exams_list_id,
                    'make_type' => $value['make_type'],
                    'make_time' => $value['make_time'],
                    'restrict_type' => $value['restrict_type'],
                    'restrict_time' => $value['restrict_time'],
                    'params' => json_encode($value['params']),
                    'staynum' => $exam['studentnum']
                    
                ]);

                foreach ($value['params'] as $param) {
                    foreach ($param['son'] as $val) {
                        if (isset($val['block'])) {
                            foreach ($val['block'] as $valu) {
                                db('exam_paper_question_list')->where(['id' => $valu['id']])->update(['setblock' => 1]);
                            }
                        } else {
                            db('exam_paper_question_list')->where(['id' => $val['id']])->update(['setblock' => 1]);
                        }
                    }
                }
            }
            $result = true;
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //更新题块
    public function saveExamPaperBlock()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id'); //科目id
        $data = $this->request->param('data/a'); //参数内容
        if (!$exams_list_id)
            $this->error('未知参数！');
        if (!is_array($data))
            $this->error('参数格式错误！');
        $exam = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exam)
            $this->error('单科错误！');

        $result = false;
        Db::startTrans();
        try {
            foreach ($data as $key => $value) {
                $score = 0;
                foreach ($value['params'] as $param) {
                    $score = bcadd($score, $param['score']);
                }
                if (isset($value['content']) && $value['content'] != null) {
                    $content = json_encode($value['content']);
                } else {
                    $content = null;
                }
                if (isset($value['id']) && $value['id']) {
                    $block = db('exam_paper_block')->where(['id' => $value['id']])->find();
                    if (!$block)
                        $this->error('未找到相关题块信息，请重试！');
                    $blockparams = json_decode($block['params'], true);
                    foreach ($blockparams as $param) {
                        foreach ($param['son'] as $val) {
                            if (isset($val['block'])) {
                                foreach ($val['block'] as $valu) {
                                    db('exam_paper_question_list')->where(['id' => $valu['id']])->update(['setblock' => 0]);
                                }
                            } else {
                                db('exam_paper_question_list')->where(['id' => $val['id']])->update(['setblock' => 0]);
                            }
                        }
                    }
                    db('exam_paper_block')->where(['id' => $value['id']])->delete();

                    $key = 'makeBlock' . $value['id'];
                    db('task')->where(['exams_list_id' => $exams_list_id, 'block_id' => $block['id']])->delete();
                    db('exam_paper_block')->insert([
                        'name' => $value['name'],
                        'score' => $score,
                        'exams_id' => $exam['exams_id'],
                        'exams_list_id' => $exams_list_id,
                        'make_type' => $value['make_type'],
                        'make_time' => $value['make_time'],
                        'restrict_type' => $value['restrict_type'],
                        'restrict_time' => $value['restrict_time'],
                        'params' => json_encode($value['params']),
                        'content' => $content,
                        'type' => $value['type'],
                        'teacher_ids' => $value['teacher_ids'],
                        'allot_type' => $value['allot_type'],
                        'judge_id' => $value['judge_id'],
                        'staynum' => $exam['studentnum'],
                        
                    ]);

                    foreach ($value['params'] as $param) {
                        foreach ($param['son'] as $val) {
                            if (isset($val['block'])) {
                                foreach ($val['block'] as $valu) {
                                    db('exam_paper_question_list')->where(['id' => $valu['id']])->update(['setblock' => 1]);
                                }
                            } else {
                                db('exam_paper_question_list')->where(['id' => $val['id']])->update(['setblock' => 1]);
                            }
                        }
                    }
                    db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id']])->delete();
                } else {

                    db('exam_paper_block')->insert([
                        'name' => $value['name'],
                        'score' => $score,
                        'exams_id' => $exam['exams_id'],
                        'exams_list_id' => $exams_list_id,
                        'make_type' => $value['make_type'],
                        'make_time' => $value['make_time'],
                        'restrict_type' => $value['restrict_type'],
                        'restrict_time' => $value['restrict_time'],
                        'params' => json_encode($value['params']),
                        // 'content' => $content,
                        // 'type' => $value['type'],
                        // 'teacher_ids' => $value['teacher_ids'],
                        // 'allot_type' => $value['allot_type'],
                        // 'judge_id' => $value['judge_id'],
                        'staynum' => $exam['studentnum']
                    ]);

                    foreach ($value['params'] as $param) {
                        foreach ($param['son'] as $val) {
                            if (isset($val['block'])) {
                                foreach ($val['block'] as $valu) {
                                    db('exam_paper_question_list')->where(['id' => $valu['id']])->update(['setblock' => 1]);
                                }
                            } else {
                                db('exam_paper_question_list')->where(['id' => $val['id']])->update(['setblock' => 1]);
                            }
                        }
                    }
                }
            }
            db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->update(['zhudivide' => null, 'ispart' => 0]);

            $result = true;
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //题块列表
    public function getExamPaperBlockList()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->get('exams_list_id'); //科目id
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exam = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exam)
            $this->error('单科错误！');
        $list = db('exam_paper_block')->where(['exams_id' => $exam['exams_id'], 'exams_list_id' => $exams_list_id])->select();
        foreach ($list as &$value) {
            $value['params'] = json_decode($value['params'], true);
            $value['content'] = json_decode($value['content'], true);
            $namearr = [];
            foreach ($value['params'] as $param) {
                foreach ($param['son'] as $val) {
                    $namearr[] = $val['name'];
                }
            }
            $value['name_text'] = $namearr;
            $teacher = db('user')->where('id', 'in', $value['teacher_ids'])->column('nickname');
            $value['teacher_text'] = implode(',', $teacher);
            $value['exam_status'] = $exam['status'];
        }
        $this->success('题块列表', $list);
    }

    //删除题块
    public function delExamPaperBlock()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $id = $this->request->get('id'); //题块id
        if (!$id)
            $this->error('未知参数！');
        $block = db('exam_paper_block')->where(['id' => $id])->find();
        if (!$block)
            $this->error('未找到相关题块信息，请重试！');
        $blockparams = json_decode($block['params'], true);
        foreach ($blockparams as $param) {
            foreach ($param['son'] as $val) {
                if (isset($val['block'])) {
                    foreach ($val['block'] as $valu) {
                        db('exam_paper_question_list')->where(['id' => $valu['id']])->update(['setblock' => 0]);
                    }
                } else {
                    db('exam_paper_question_list')->where(['id' => $val['id']])->update(['setblock' => 0]);
                }
            }
        }
        db('exam_paper_block')->where(['id' => $id])->delete();
        $key = 'makeBlock' . $id;
        db('task')->where(['exams_list_id' => $block['exams_list_id'], 'key' => $key])->delete();
        db('exam_paper_images')->where(['exams_list_id' => $block['exams_list_id']])->update(['zhudivide' => null, 'ispart' => 0]);
        db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $id])->delete();
        $this->success('操作成功！');
    }

    //题块任务设置
    public function setBlockTask()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //题块id
        $type = $this->request->post('type'); //评阅方式 单评=alone ,双评=dual
        $teacher_ids = $this->request->post('teacher_ids'); //阅卷老师多个以逗号分隔
        $allot_type = $this->request->post('allot_type'); //阅卷分配:1=平均分配,2=效率优先,3=定量分配
        $judge_id = $this->request->post('judge_id'); //仲裁老师id
        $threshold = $this->request->post('threshold'); //双评阈值
        if (!$id)
            $this->error('未知参数！');
        $block = db('exam_paper_block')->where(['id' => $id])->find();
        if (!$block)
            $this->error('未找到相关题块信息，请重试！');
        if (in_array($type, ['alone', 'dual'])) {
            if($type === 'alone'){
                db('exam_paper_block')->where(['id' => $id])->update(['type' => $type]);
            }else{
                // if(!$threshold) $this->error('未知参数！');
                db('exam_paper_block')->where(['id' => $id])->update(['type' => $type,'threshold'=>$threshold]);
            }
            
        }
        if ($teacher_ids) {
            db('exam_paper_block')->where(['id' => $id])->update(['teacher_ids' => $teacher_ids]);
            $examStatus = db('exam_list')->where(['id' => $block['exams_list_id']])->value('status');
            // if ($examStatus == 6) {
            //     db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $id])->delete();
            // }
        }
        if (in_array($allot_type, [1, 2, 3])) {
            db('exam_paper_block')->where(['id' => $id])->update(['allot_type' => $allot_type]);
        }
        if ($judge_id) {
            db('exam_paper_block')->where(['id' => $id])->update(['judge_id' => $judge_id]);
        }

        $this->success('操作成功！');
    }

    //设置科目进度
    public function setExamListStatus()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id'); //科目id
        $setanswercard = $this->request->post('setanswercard', ''); //答题卡设置状态
        $setmark = $this->request->post('setmark', ''); //阅卷设置状态
        $iskuang = $this->request->post('iskuang', ''); //框选题块
        if (!$exams_list_id)
            $this->error('未知参数！');
        $update = [];
        if ($setanswercard) {
            $update['setanswercard'] = $setanswercard;
        }
        if ($setmark) {
            $update['setmark'] = $setmark;
        }
        if ($iskuang) {
            $update['iskuang'] = $iskuang;
        }
        db('exam_list')->where(['id' => $exams_list_id])->update($update);
        $this->success('操作成功！');
    }


    //考号区坐标
    public function markingArea()
    {
        if (!$this->request->isGet())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->get('exams_list_id'); //科目id
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exam = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exam)
            $this->error('单科错误！');
        $area = db('exam_paper_marking_area')->where(['exams_id' => $exam['exams_id'], 'exams_list_id' => $exams_list_id])->find();
        if ($area) {
            $area['location'] = json_decode($area['location'], true);
            $area['content'] = json_decode($area['content'], true);
            $area['keguanti'] = json_decode($area['keguanti'], true);
        }
        $this->success('考号区坐标', $area);
    }


    //题块坐标参数及图片
    public function setBlockContent()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //题块id
        $image = $this->request->post('image');
        $content = $this->request->param('content/a'); //参数内容
        if (!$id)
            $this->error('未知参数！');
        $block = db('exam_paper_block')->where(['id' => $id])->find();
        if (!$block)
            $this->error('未找到相关题块信息，请重试！');

        if ($image) {
            db('exam_paper_block')->where(['id' => $id])->update(['image' => $image]);
        }
        if (is_array($content) && !empty($content)) {
            db('exam_paper_block')->where(['id' => $id])->update(['content' => json_encode($content)]);
        } else {
            db('exam_paper_block')->where(['id' => $id])->update(['content' => null]);
        }
        db('exam_paper_images')->where(['exams_list_id' => $block['exams_list_id']])->update(['zhudivide' => null, 'ispart' => 0]);
        $this->success('操作成功！');
    }

    //读取扫描答题卡图片列表
    public function getExamPaperImage()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $batchnum = $this->request->post('batchnum');
        $page = $this->request->post('page', 1);
        $pagesize = $this->request->post('pagesize', 10);
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        if (!$exams_id)
            $this->error('未找到相关试卷信息！');
        $list = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id])->where(function ($query) use ($batchnum) {
            if ($batchnum) {
                $query->where(['batchnum' => $batchnum]);
            }
        })->order('createtime desc')->paginate($pagesize, false, ['page' => $page])->each(function ($item, $index) {

            return $item;
        });
        $this->success('扫描答题卡图片列表', $list);
    }

    //答题卡信息
    public function examPaperImage()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id)
            $this->error('未知参数！');
        $list = db('exam_paper_images')->where(['id' => $id])->find();
        if ($list) {
            $list['kanswer'] = json_decode($list['kanswer'], true);
        }
        $this->success('扫描答题卡图片列表', $list);
    }

    //读取扫描信息
    public function getExamPaperImageInfo()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $type = $this->request->post('type'); //方式 1=批次，2=班级
        if (!$exams_list_id || !in_array($type, [1, 2]))
            $this->error('未知参数！');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        if (!$exams_id)
            $this->error('未找到相关试卷信息！');

        switch ($type) {
            case '1':
                #批次
                $list = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id])->field('batchnum')->group('batchnum')->select();
                foreach ($list as &$value) {
                    $uplodenum = db('exam_paper_images')->where(['batchnum' => $value['batchnum'], 'exams_list_id' => $exams_list_id])->group('key')->count();
                    $unusual = db('exam_paper_images')->where(['batchnum' => $value['batchnum'], 'exams_list_id' => $exams_list_id, 'unusual' => 1])->group('key')->count();
                    $value['uplodenum'] = $uplodenum;
                    $value['unusual'] = $unusual;
                }
                break;
            case '2':
                $list = [];
                break;
        }

        $this->success('扫描信息', $list);
    }

    //考号对比
    public function examNumberContrast()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams = $this->request->post('exam/a'); //客观题答案
        if (!is_array($exams) || empty($exams))
            $this->error('未知参数！');

        foreach ($exams as $key => $answer) {
            $info = db('exam_paper_images')->where(['id' => $answer['id']])->find();
            if ($info) {
                $examInfo = db('exams')->where(['id' => $info['exams_id']])->find();
                if (!$examInfo) {
                    // db('exam_paper_images')->where('key', $info['key'])->delete();
                    db('exam_paper_images')->where('key', $info['key'])->update([
                        'status' => -1
                    ]);

                } else {
                    $schoolIds = explode(',', $examInfo['school_ids']);
                    $classIds = $examInfo['class_ids'] ? explode(',', $examInfo['class_ids']) : '';
                    $student = db('student')->where('school_id', 'in', $schoolIds)
                        ->where(['grade_id' => $examInfo['grade_id'], 'exam_number' => $answer['examNo']])
                        ->where(function ($query) use ($classIds) {
                            if ($classIds) {
                                $query->where('class_id', 'in', $classIds);
                            }
                        })
                        ->find();
                    if ($student) {
                        //检测考号是否重复
                        $check = db('exam_paper_images')->where(['exams_id' => $info['exams_id'], 'exams_list_id' => $info['exams_list_id'], 'student_id' => $student['id']])->find();
                        if (!$check) {
                            db('exam_paper_images')->where('key', $info['key'])->update([
                                'student_id' => $student['id'],
                                'school_id' => $student['school_id'],
                                'student_name' => $student['name'],
                                'exam_number' => $student['exam_number'],
                                'class_id' => $student['class_id'],
                                'grade_id' => $student['grade_id'],
                                'stu_number' => $student['stu_number'],
                                'status' => 1
                            ]);

                        } else {
                            db('exam_paper_images')->where('key', $info['key'])->update([
                                'student_id' => $student['id'],
                                'school_id' => $student['school_id'],
                                'student_name' => $student['name'],
                                'exam_number' => $student['exam_number'],
                                'class_id' => $student['class_id'],
                                'grade_id' => $student['grade_id'],
                                'stu_number' => $student['stu_number'],
                                'status' => 1
                            ]);

                            db('exam_paper_images')->where('student_id', $student['id'])->update([
                                'status' => -4
                            ]);
                        }
                    } else {
                        db('exam_paper_images')->where('key', $info['key'])->update([
                            'status' => -1
                        ]);

                    }
                }
            }
        }
        $this->success('操作成功');
    }

    //手动添加考号
    public function setExamNumber()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $id = $this->request->post('id');
        $exam_number = $this->request->post('exam_number'); //考号
        $type = $this->request->post('type', 0); //类型
        if (!$exams_list_id || !$id)
            $this->error('未知参数！');
        $info = db('exam_paper_images')->where(['id' => $id, 'exams_list_id' => $exams_list_id])->find();
        if (!$info)
            $this->error('未找到相关信息！');
        $exams = db('exams')->where(['id' => $info['exams_id']])->find();
        if (!$exams)
            $this->error('未找到相关信息！');
        $schoolIds = explode(',', $exams['school_ids']);

        $student = db('student')->where('school_id', 'in', $schoolIds)->where(['grade_id' => $exams['grade_id'], 'exam_number' => $exam_number])->find();
        if ($student) {
            $check = db('exam_paper_images')->where(['exam_number' => $student['exam_number'], 'exams_list_id' => $exams_list_id])->find();
            if (!$check) {
                db('exam_paper_images')->where('key', $info['key'])->update([
                    'student_id' => $student['id'],
                    'school_id' => $student['school_id'],
                    'student_name' => $student['name'],
                    'exam_number' => $student['exam_number'],
                    'class_id' => $student['class_id'],
                    'grade_id' => $student['grade_id'],
                    'stu_number' => $student['stu_number'],
                    'status' => -2
                ]);


                if ($type > 0) {
                    db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'student_id' => $info['student_id']])->update([
                        'status' => -2
                    ]);
                }
            } else {
                db('exam_paper_images')->where('key', $info['key'])->update([
                    'student_id' => $student['id'],
                    'school_id' => $student['school_id'],
                    'student_name' => $student['name'],
                    'exam_number' => $student['exam_number'],
                    'class_id' => $student['class_id'],
                    'grade_id' => $student['grade_id'],
                    'stu_number' => $student['stu_number'],
                    'status' => 1
                ]);

                db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'student_id' => $student['id']])->update([
                    'status' => -4
                ]);

                if ($type > 0) {
                    db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'student_id' => $info['student_id']])->update([
                        'status' => -2
                    ]);
                }
            }
        } else {
            $this->error('操作失败');
        }
        db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'student_id' => $info['student_id']])->update([ 'ispart' => 0]);
        $this->success('操作成功');
    }

    //客观题异常处理
    public function objectiveItem()
    {
        if (!$this->request->isPost()) $this->error('请求方式错误');
        $id = $this->request->post('id'); //答题卡id
        $kanswer = $this->request->post('kanswer/a'); //客观题答案
        if (!$id ||!is_array($kanswer) || empty($kanswer)) $this->error('未知参数！');
        $paper = db('exam_paper_images')->where('id', $id)->find();
        if(!$paper) $this->error('未找到相关答题卡信息！');
        db('exam_paper_images')->where('id', $id)->update([
            'kanswer' => json_encode([$kanswer])
        ]);
        db('exam_paper_images')->where('key', $paper['key'])->update([
            'status' => 2
        ]);

        //判断是否扫描完成
        $saonum = db('exam_paper_images')->where(['status' => 2, 'page' => 1])->count();
        $examsList = db('exam_list')->where(['id' => $paper['exams_list_id']])->find();
        if ($saonum == $examsList['studentnum']) {
            db('exam_list')->where(['id' => $examsList['id']])->update(['scancard' => 2]);
        }

        $this->success('操作成功');
    }


    //客观题对比
    public function keguantiContrast()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $submit = $this->request->post('submit', 0); //提交状态
        $kanswer = $this->request->post('kanswer/a'); //客观题答案

        if (!is_array($kanswer) || empty($kanswer))
            $this->error('未知参数！');
        //客观题得分
        $scoresum = 0;
        foreach ($kanswer as $key => $answer) {
            $paper = db('exam_paper_images')->where('id', $answer['id'])->find();
            
            if ($paper && $paper['status'] == 2) {
                continue;
            } elseif ($paper && $paper['status'] == -1) {
                db('exam_paper_images')->where('id', $answer['id'])->update([
                    'kanswer' => json_encode([$kanswer[$key]]),
                ]);
            } elseif ($paper && $paper['status'] == -3) {
                db('exam_paper_images')->where('id', $answer['id'])->update([
                    'kanswer' => json_encode([$kanswer[$key]]),
                ]);
            } elseif ($paper && $paper['status'] == -4) {
                db('exam_paper_images')->where('id', $answer['id'])->update([
                    'kanswer' => json_encode([$kanswer[$key]]),
                ]);
            } elseif ($paper && in_array($paper['status'], [1, -2])) {
                $status = $paper['status'];
                $data = [];
                $restult = '';
                for ($i = 0; $i < count($answer['choiceAnswers']); $i++) {
                    $exams_list = db('exam_paper_question_list')->where(['exams_list_id' => $paper['exams_list_id'], 'key' => $answer['choiceAnswers'][$i]['qsnum'], 'type' => 'KG'])->field('id,name,key,answer,score')->find();
                    if ($exams_list['answer']) {
                        if (!empty($answer['choiceAnswers'][$i]['selAnswer'])) {
                            $selAnswer = $answer['choiceAnswers'][$i]['selAnswer'];
                            // $selAnswerarr = explode(',', $selAnswer);
                            // $selAnswer = implode(',', $selAnswerarr);
                            if ($exams_list['answer'] === $selAnswer) {
                                $scoresum = bcadd($scoresum, $exams_list['score'], 0);
                                $status = 2;
                                $restult = 'true';
                            } else {
                                $status = 2;
                                $restult = 'false';
                            }
                        } else {
                            if ($submit > 0) {
                                $status = 2;
                                $restult = 'false';
                            } else {
                                
                                $status = -2;
                            }
                        }
                    } else {
                        
                        $status = -2;
                    }
                    if ($restult === 'true') {
                        $score = $exams_list['score'];
                    } else {
                        $score = 0;
                    }
                    $data[$i] = [
                        'exams_id' => $paper['exams_id'],
                        'exams_list_id' => $paper['exams_list_id'],
                        'student_id' => $paper['student_id'],
                        'school_id' => $paper['school_id'],
                        'key' => $answer['choiceAnswers'][$i]['qsnum'],
                        'answer' => $answer['choiceAnswers'][$i]['selAnswer'],
                        'restult' => $restult,
                        'name' => $exams_list['name'],
                        'score' => $score,
                        'rightScore' => $exams_list['score'],
                        'rightAnswer' => $exams_list['answer']
                    ];
                }
                $up = db('exam_paper_images')->where('id', $paper['id'])->update([
                    'kanswer' => json_encode([$kanswer[$key]]),
                    'kanswerresult' => json_encode($data),
                    'scoresum' => $scoresum
                ]);
                
                if ($status == 2) {
                    db('exam_paper_images')->where('key', $paper['key'])->update([
                        'status' => 2
                    ]);

                    $examStatus = db('exam_list')->where(['id' => $paper['exams_list_id']])->value('status');
                    if ($examStatus == 3) {
                        //写入阅卷任务表
                        Task::addOneTask($paper['exams_list_id'], $paper['id']);
                    }
                } else {
                    
                    db('exam_paper_images')->where('key', $paper['key'])->update([
                        'status' => $status
                    ]);
                }
            } else {
               
                db('exam_paper_images')->where('id', $answer['id'])->update([
                    'kanswer' => json_encode([$kanswer[$key]])
                ]);
                db('exam_paper_images')->where('key', $paper['key'])->update([
                    'status' => -2
                ]);
            }
        }
        //判断是否扫描完成
        $saonum = db('exam_paper_images')->where(['status' => 2, 'page' => 1])->count();
        $examsList = db('exam_list')->where(['id' => $paper['exams_list_id']])->find();
        if ($saonum == $examsList['studentnum']) {
            db('exam_list')->where(['id' => $examsList['id']])->update(['scancard' => 2]);
        }

        $this->success('操作成功');
    }

    //客观题异常答题卡信息
    public function kexamPaperImage()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $key = $this->request->post('key');
        if (!$key)
            $this->error('未知参数！');
        $list = db('exam_paper_images')->where(['key' => $key])->select();
        foreach ($list as $key => &$value) {
            $value['kanswer'] = json_decode($value['kanswer'], true);
        }
        $this->success('扫描答题卡图片列表', $list);
    }

    //设为异常
    public function setUnusual()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $paperKey = $this->request->post('paperKey/a'); //未识别正反面答题卡处理
        if (!is_array($paperKey))
            $this->error('未知参数！');
        $paperKeyArray = array_column($paperKey, 'key');
        $paperKeyArray = array_unique($paperKeyArray);
        if (!empty($paperKeyArray)) {
            foreach ($paperKeyArray as $value) {
                db('exam_paper_images')->where(['key' => $value])->update(['status' => -3,'ispart'=>0]);
            }
        }
        $this->success('操作成功');
    }

    //试卷异常列表
    public function unusualExamPaperImage()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $type = $this->request->post('type');
        if (!$exams_list_id || !in_array($type, [1, 2, 3, 4]))
            $this->error('未知参数！');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        if (!$exams_id)
            $this->error('未找到相关试卷信息！');
        switch ($type) {
            case '1':
                #考号异常
                $group = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'status' => -1])->field('key')->group('key')->select();
                $list = [];
                foreach ($group as $key => $value) {
                    $papers = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'key' => $value['key']])->select();
                    foreach ($papers as &$val) {
                        $val['student'] = [];
                        $val['kanswer'] = json_decode($val['kanswer'], true);
                        $val['userName'] = db('user')->where(['id' => $val['user_id']])->value('nickname');
                        $val['createtime_text'] = date('Y-m-d H:i:s', $val['createtime']);
                    }
                    $list[] = $papers;
                }

                break;
            case '2':
                #客观题异常
                $list = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'status' => -2, 'page' => 1])->select();
                foreach ($list as $key => &$value) {
                    $val['student'] = [];
                    $value['kanswer'] = json_decode($value['kanswer'], true);
                    $val['userName'] = db('user')->where(['id' => $value['user_id']])->value('nickname');
                    $value['createtime_text'] = date('Y-m-d H:i:s', $value['createtime']);
                }
                break;
            case '3':
                #定位异常
                $group = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'status' => -3])->field('key')->group('key')->select();
                $list = [];
                foreach ($group as $key => $value) {
                    $papers = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'key' => $value['key']])->select();
                    foreach ($papers as &$val) {
                        $val['student'] = [];
                        $val['kanswer'] = json_decode($val['kanswer'], true);
                        $val['userName'] = db('user')->where(['id' => $val['user_id']])->value('nickname');
                        $val['createtime_text'] = date('Y-m-d H:i:s', $val['createtime']);
                    }
                    $list[] = $papers;
                }

                break;
            case '4':
                #考号重复
                $group = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'status' => -4])->field('student_id')->group('student_id')->select();
                $list = [];
                foreach ($group as $value) {
                    $keyGroup = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'student_id' => $value['student_id']])->field('key')->group('key')->select();
                    $keyArr = [];
                    foreach ($keyGroup as &$valu) {
                        $papers = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'key' => $valu['key']])->select();
                        foreach ($papers as &$val) {
                            if ($value['student_id']) {
                                $student = db('student')->where(['id' => $val['student_id']])->find();
                                if ($student) {
                                    $schoolName = db('school')->where('id', $student['school_id'])->value('name');
                                    $student['schoolName'] = $schoolName;
                                }
                                $value['student'] = $student;
                            } else {
                                $value['student'] = [];
                            }
                            $val['kanswer'] = json_decode($val['kanswer'], true);
                            $val['userName'] = db('user')->where(['id' => $val['user_id']])->value('nickname');
                            $val['createtime_text'] = date('Y-m-d H:i:s', $val['createtime']);
                        }
                        $keyArr[] = $papers;
                    }
                    $list[] = $keyArr;
                }

                break;
            default:
                $list = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'page' => 1])->where('status', 'in', [-1, -2])->select();
                foreach ($list as $key => &$value) {
                    if ($value['student_id']) {
                        $student = db('student')->where(['id' => $value['student_id']])->find();
                        if ($student) {
                            $schoolName = db('school')->where('id', $student['school_id'])->value('name');
                            $student['schoolName'] = $schoolName;
                        }
                        $value['student'] = $student;
                    } else {
                        $value['student'] = [];
                    }
                    $value['userName'] = db('user')->where(['id' => $value['user_id']])->value('nickname');
                    $value['createtime_text'] = date('Y-m-d H:i:s', $value['createtime']);
                }
                break;
        }


        $this->success('试卷异常列表', $list);
    }

    //定位异常
    public function changeStatus()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $key = $this->request->post('key');
        if (!$key || !$exams_list_id)
            $this->error('参数错误！');
        db('exam_paper_images')->where(['key' => $key, 'exams_list_id' => $exams_list_id])->update(['status' => 1,'ispart'=>0]);
        $this->success('操作成功');
    }

    //删除考卷
    public function delExamPaper()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $ids = $this->request->post('ids');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$ids || !$exams_list_id)
            $this->error('参数错误！');
        $list = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->where('id', 'in', $ids)->select();

        $studentIdArr = [];
        foreach ($list as $value) {
            db('exam_paper_images')->where('key', $value['key'])->delete();
            $studentIdArr[] = $value['student_id'];
        }
        // db('exam_list')->where('id', $exams_list_id)->setDec('scannum', $count);
        $studentIdArr = array_unique($studentIdArr);
        if(!empty($studentIdArr)){
            foreach ($studentIdArr as $studentId) {
                if($studentId){
                    $count = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'student_id' => $studentId])->count();
                    if ($count == 2) {
                        db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'student_id' => $studentId])->update(['status' => -2]);
                    }
                    db('exam_teacher_make_log')->where('student_id', $studentId)->where(['exams_list_id' => $exams_list_id])->delete();
                    db('task')->where('student_id', $studentId)->where(['exams_list_id' => $exams_list_id])->delete();
                }  
            }
            
        }
        
        $this->success('操作成功！');
    }

    //删除考卷
    public function delPaper()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $ids = $this->request->post('ids');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$ids || !$exams_list_id)
            $this->error('参数错误！');
        $list = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->where('id', 'in', $ids)->select();

        foreach ($list as $value) {
            db('exam_paper_images')->where('key', $value['key'])->delete();
        }
        $this->success('操作成功！');
    }

    //客观题异常设为正常
    public function setExamPaperNormal()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $ids = $this->request->post('ids');
        if (!$ids)
            $this->error('参数错误！');
        $list = db('exam_paper_images')->where('id', 'in', $ids)->select();
        $examslistid = [];
        foreach ($list as $key => $value) {
            $examslistid[] = $value['exams_list_id'];
            db('exam_paper_images')->where('key', $value['key'])->update(['status' => 2]);
        }

        array_unique($examslistid);

        $examslistid = implode(',', $examslistid);
        if ($examslistid) {
            //写入阅卷任务表
            Task::addTask($examslistid);
        }
        //判断是否扫描完成
        $saonum = db('exam_paper_images')->where(['status' => 2, 'page' => 1])->count();
        $examsList = db('exam_list')->where(['id' => $examslistid])->find();
        if ($saonum == $examsList['studentnum']) {
            db('exam_list')->where(['id' => $examsList['id']])->update(['scancard' => 2]);
        }
        $this->success('操作成功！');
    }

    protected $statusText = ['0' => '未识别', '1' => '识别中', '2' => '已完成', '-1' => '考号异常待处理', '-2' => '客观题异常待处理', '-3' => '定位异常', '-4' => '考号重复'];

    //上传进度
    public function upPlan()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $status = $this->request->post('status');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_id = db('exam_list')->where(['id' => $exams_list_id])->value('exams_id');
        if (!$exams_id)
            $this->error('未找到相关试卷信息！');
        $list = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id])->where(function ($query) use ($status) {
            if (in_array($status, [-1, -2, 0, 1, 2])) {
                $query->where('status', $status);
            }
        })->select();
        if (empty($list))
            $this->success('上传进度', $list);
        foreach ($list as $key => &$value) {
            if ($value['student_id']) {
                $student = db('student')->where(['id' => $value['student_id']])->find();
                $value['student'] = $student;
            } else {
                $value['student'] = [];
            }
            $value['schoolName'] = db('school')->where('id', $value['school_id'])->value('name');
            $value['userName'] = db('user')->where(['id' => $value['user_id']])->value('nickname');
            $value['status_text'] = $this->statusText[$value['status']];
        }
        $this->success('上传进度', $list);
    }


    //扫描识别进度页
    public function schedulePaper()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        $exams_id = $exams_list['exams_id'];
        $data = [];
        //已上传试卷数 已上传试卷数=已完成入库总数+未识别试卷数+考号异常数
        $upnum = 0;
        //已完成入库总数
        $putinnum = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'page' => 1])->where('status', 'in', [2, 3, 4, 5])->count();
        $upnum = $putinnum;
        //未识别试卷数
        $noschedulenum = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'page' => 1])->where('status', 'in', [-2, -3, -4])->count();
        // $upnum = bcadd($upnum, $noschedulenum, 0);
        //考号异常数
        $examnum = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'status' => -1, 'page' => 1])->count();
        // $upnum = bcadd($upnum, $examnum, 0);
        //已完成比例 已完成比例=已完成入库总数/需扫描试卷总数*100%
        $finish = 0;
        //考生总数 = 需扫描试卷总数；
        $studentnum = $exams_list['studentnum'];
        if ($studentnum > 0) {
            $finish = round(($putinnum / $studentnum) * 100, 2);
            //缺考人数 学生总数-已完成入库总数
            $quenum = bcsub($studentnum, $putinnum, 0);
            if ($quenum < 0) {
                $quenum = 0;
            }
            //参加考试百分比
            $cannum = round(($putinnum / $studentnum) * 100, 2);
            //未完成入库总数
            $noinkunum = bcsub($studentnum, $putinnum, 0);
            if ($noinkunum < 0) {
                $noinkunum = 0;
            }
        } else {
            $quenum = 0;
            $cannum = 0;
            $noinkunum = 0;
        }

        //进度详情


        //其他异常（客观题异常）
        $list = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'status' => -2, 'page' => 1])->select();
        foreach ($list as $key => &$value) {
            if ($value['student_id']) {
                $student = db('student')->where(['id' => $value['student_id']])->find();
                // if ($student) {
                //     $schoolName = db('school')->where('id',$student['school_id'])->value('name');
                //     $student['schoolName'] = $schoolName;
                // }
                $value['student'] = $student;
            } else {
                $value['student'] = [];
            }
            $value['userName'] = db('user')->where(['id' => $value['user_id']])->value('nickname');
            $value['schoolName'] = db('school')->where('id', $value['school_id'])->value('name');
            $value['status_text'] = $this->statusText[$value['status']];
        }
        $data = [
            'upnum' => $upnum,
            //已上传试卷数
            'putinnum' => $putinnum,
            //已完成入库总数
            'noschedulenum' => $noschedulenum,
            //未识别试卷数
            'finish' => $finish,
            //已完成比例
            'studentnum' => $studentnum,
            //考生总数 = 需扫描试卷总数；
            'quenum' => $quenum,
            //缺考人数,
            'examnum' => $examnum,
            //考号异常
            'noinkunum' => $noinkunum,
            //未完成入库总数
            'cannum' => $cannum,
            //参加考试百分比
            'list' => $list //其他异常
        ];
        $this->success('扫描识别进度页', $data);
    }

    //待识别答题卡列表
    public function daiExamPaperImageList()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        $exams_id = $exams_list['exams_id'];
        $list = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'status' => 0])->group('key')->select();
        foreach ($list as $key => &$value) {
            $value['student'] = [];
            $value['userName'] = db('user')->where(['id' => $value['user_id']])->value('nickname');
            $value['schoolName'] = db('school')->where('id', $value['school_id'])->value('name');
            $value['status_text'] = $this->statusText[$value['status']];
        }
        $this->success('待识别答题卡列表', $list);
    }


    //扫描页
    public function scanPage()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        $exams_id = $exams_list['exams_id'];
        $data = [];
        $mobannum = db('exam_images')->where('exams_list_id', $exams_list_id)->count();
        $kgnum = db('exam_paper_question_list')->where(['exams_list_id' => $exams_list_id, 'type' => "KG"])->count();
        //考号异常
        $examnum = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->where('status', 'in', [-1, -3, -4])->field('key')->group('key')->count();
        //客观题异常
        $keguantinum = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'page' => 1, 'status' => -2])->count();
        //已完成入库
        $scannum = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'page' => 1])->where('status', 'in', [2, 3, 4, 5])->count();
        //已上传
        $upnum = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->field('key')->group('key')->count();
        $data = [
            'mobannum' => $mobannum,
            'kgnum' => $kgnum,
            'studentnum' => $exams_list['studentnum'],
            'scannum' => $scannum,
            'examnum' => $examnum,
            'keguantinum' => $keguantinum,
            'upnum' => $upnum
        ];
        $this->success('扫描页', $data);
    }

    //按批次删除考卷
    public function delBatchExamPaper()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $batchnum = $this->request->post('batchnum');
        if (!$exams_list_id || !$batchnum)
            $this->error('未知参数！');
        $count = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'batchnum' => $batchnum])->group('key')->count();
        $list = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'batchnum' => $batchnum])->group('key')->select();
        // db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'batchnum' => $batchnum])->delete();
        foreach ($list as $key => $value) {
            db('exam_paper_images')->where(['key' => $value['key']])->delete();
            // if ($value['status'] == -4) {
            //     db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'student_id' => $value['student_id']])->update(['status' => -2]);
            // }
            if ($value['student_id']) {
                db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'student_id' => $value['student_id']])->delete();
                db('task')->where(['exams_list_id' => $exams_list_id, 'student_id' => $value['student_id']])->delete();
            }


        }
        // db('exam_list')->where('id', $exams_list_id)->setDec('scannum', $count);

        $this->success('操作成功！');
        // $del = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'batchnum' => $batchnum])->delete();
        // if ($del) {
        //     db('exam_list')->where('id', $exams_list_id)->setDec('scannum', $count);
        //     $this->success('操作成功！');
        // } else {
        //     $this->error('操作失败！');
        // }
    }

    //获取学生列表
    public function getStudentLiset()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $keyword = $this->request->post('keyword');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        $exams = db('exams')->where(['id' => $exams_list['exams_id']])->find();
        if (!$exams)
            $this->error('未找到相关试卷信息！');
        $schoolIds = explode(',', $exams['school_ids']);
        $classIds = $exams['class_ids'] ? explode(',', $exams['class_ids']) : '';
        $studentIds = [];
        $paperList = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->field('student_id')->select();
        foreach ($paperList as $key => $paper) {
            if ($paper['student_id']) {
                $studentIds[] = $paper['student_id'];
            }
        }
        $studentIds = array_unique($studentIds);
        //->where('id','not in',$studentIds)
        $list = db('student')->where('school_id', 'in', $schoolIds)->where(['grade_id' => $exams['grade_id']])->where(function ($query) use ($classIds) {
            if ($classIds) {
                $query->where('class_id', 'in', $classIds);
            }
        })
            ->where(function ($query) use ($keyword) {
                if ($keyword) {

                    $query->where('name|exam_number', 'like', '%' . $keyword . '%');
                }
            })
            ->field('id,name,exam_number')->select();
        $this->success('学生列表', $list);
    }


    //删除模版
    public function delImages()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id)
            $this->error('未知参数！');
        db('exam_images')->where(['exams_list_id' => $exams_list_id])->delete();
        db('exam_paper_marking_area')->where(['exams_list_id' => $exams_list_id])->delete();
        db('exam_list')->where(['id' => $exams_list_id])->update(['setanswercard' => 0, 'iskuang' => 0]);
        $this->success('操作成功！');
    }

    //面包屑信息
    public function examInfo()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id])->field('id,name,exams_id')->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        $exams_id = $exams_list['exams_id'];
        $exams = db('exams')->where(['id' => $exams_id])->field('id,name')->find();
        $list = db('exam_list')->where(['exams_id' => $exams_id])->field('id,name,setanswercard,setmark,scancard')->select();
        $data = [
            'info' => $exams_list,
            'exams' => $exams,
            'list' => $list
        ];
        $this->success('面包屑信息', $data);
    }

    //开始阅卷
    public function setExamStatus()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        // if ($exams_list['setanswercard'] == 0 || $exams_list['setmark'] == 0) $this->error('请先完成阅卷设置或扫描！'); //|| in_array($exams_list['scancard'], [0, 1]) 
        $yichang = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->where('status', 'in', [-1, -2, -3, -4])->find();
        if ($yichang)
            $this->error('有异常未处理，无法开始阅卷！');
        $nopart = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->where('ispart', 0)->find();
        if ($nopart)
            $this->error('有未完成的切图，无法开始阅卷！');
        //写入阅卷任务表
        Task::addTask($exams_list_id);

        //判断题块是否设置阅卷老师
        $blockList = db('exam_paper_block')->where('exams_list_id', $exams_list_id)->select();
        foreach ($blockList as $key => $value) {
            if (!$value['teacher_ids']) {
                $this->error('请先设置阅卷老师！');
            }
        }

        db('exam_list')->where('id', $exams_list_id)->update(['status' => 2]);
        db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->where('status', 'in', [2, 4])->update(['status' => 3]);
        db('exam_paper_block')->where('exams_list_id', $exams_list_id)->update(['status' => 1]);
        $this->success('操作成功！');
    }

    //暂停阅卷
    public function pauseExamStatus()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id, 'status' => 2])->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        $blockList = db('exam_paper_block')->where('exams_list_id', $exams_list_id)->select();
        foreach ($blockList as $key => $value) {
            $key = 'makeBlock' . $value['id'];
            db('task')->where(['exams_list_id' => $value['exams_list_id'], 'key' => $key])->delete();
        }
        db('exam_list')->where('id', $exams_list_id)->update(['status' => 6]);
        db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'status' => 3])->update(['status' => 4]);
        db('exam_paper_block')->where('exams_list_id', $exams_list_id)->update(['status' => 3]);
        $this->success('操作成功！');
    }


    //一键统分
    public function setTotalScore()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id)
            $this->error('未知参数！');
        //考试信息
        $exams = db('exams')->where(['id' => $id])->find();
        if (empty($exams))
            $this->error('未找到相关考试信息!');
        //判断考试是否阅卷完成
        //科目总数
        $examListNum = db('exam_list')->where(['exams_id' => $id])->count();
        //待统分科目总数
        $overTaskNum = db('exam_list')->where(['exams_id' => $id, 'status' => 3])->count();
        // if ($examListNum != $overTaskNum) $this->error('有未完成阅卷的科目，无法统分！');
        $ids = db('exam_list')->where(['exams_id' => $id])->where('status', 'in', [2, 3, 6])->column('id');
        if (empty($ids))
            $this->error('未找到满足条件的单科!');
        $yichang = db('exam_paper_images')->where(['exams_id' => $id])->where('status', 'in', [0, -1, -2, -3, -4])->find();
        if ($yichang)
            $this->error('有异常未处理，无法统分！');
        $nopart = db('exam_paper_images')->where(['exams_id' => $id])->where('ispart', 0)->find();
        if ($nopart)
            $this->error('有未完成的切图，无法统分！');
        $checkanswer = db('exam_paper_question_list')->where(['exams_id'=>$id,'type'=>'KG','answer'=> null])->find();
        if ($checkanswer)  $this->error('未设置客观题答案,无法统分！');

        //进行客观题对比
        $kResult = Papers::computeScore($id);
        if (!$kResult) $this->error('客观题对比异常,无法统分！');
        //单科统分
        $return = Papers::subjectScore($ids);
        if (!empty($return)) {
            foreach ($return as $ret) {
                db('exam_paper_student_list')->insertGetId($ret);
            }
        }
        //班级信息
        if ($exams['class_ids']) {
            $classIds = explode(',', $exams['class_ids']);
        } else {
            $classIds = db('school_class')->where(['grade_id' => $exams['grade_id']])->colums('id');
        }
        foreach ($ids as $exams_list_id) {
            //排名
            $list = db('exam_paper_student_list')->where(['exams_list_id' => $exams_list_id])->select();
            if ($list) {
                //按学校分组
                Papers::setRank($list, 'school_id', 'exam_paper_student_list', 'schoolrank');
                $lgradeExamList = db('exam_paper_student_list')->where(['exams_list_id' => $exams_list_id, 'grade_id' => $exams['grade_id']])->select();
                if ($lgradeExamList) {
                    //按年级
                    Papers::setRank($lgradeExamList, 'grade_id', 'exam_paper_student_list', 'graderank');
                }
                foreach ($classIds as $classid) {
                    $lclassExamList = db('exam_paper_student_list')->where(['exams_list_id' => $exams_list_id, 'class_id' => $classid])->select();
                    if ($lclassExamList) {
                        //按班级
                        Papers::setRank($lclassExamList, 'class_id', 'exam_paper_student_list', 'classrank');
                    }

                }
            }

        }

        //考试统分
        $restult = Papers::totalScore($id);
        if (!empty($restult)) {
            foreach ($restult as $ret) {
                db('exam_paper_student')->insertGetId($ret);
            }
        }
        //排名
        $examList = db('exam_paper_student')->where(['exams_id' => $id])->select();
        if ($examList) {
            //按学校分组
            Papers::setRank($examList, 'school_id', 'exam_paper_student', 'schoolrank');
            $gradeExamList = db('exam_paper_student')->where(['exams_id' => $id, 'grade_id' => $exams['grade_id']])->select();
            if ($gradeExamList) {
                //按年级
                Papers::setRank($gradeExamList, 'grade_id', 'exam_paper_student', 'graderank');
            }
            //按班级
            foreach ($classIds as $classid) {
                $classExamList = db('exam_paper_student')->where(['exams_id' => $id, 'class_id' => $classid])->select();
                if ($classExamList) {
                    Papers::setRank($classExamList, 'class_id', 'exam_paper_student', 'classrank');
                }

            }
        }


        db('exam_list')->where('id', 'in', $ids)->update(['status' => 4]);
        db('exams')->where('id', $id)->update(['status' => 4]);
        db('exam_paper_images')->where('exams_list_id', 'in', $ids)->update(['status' => 4]);

        $this->success('操作成功！');
    }

    //取消统分
    public function cancelTotalScore()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id)
            $this->error('未知参数！');

        db('exam_paper_student_list')->where('exams_id', $id)->delete();
        db('exam_paper_student')->where('exams_id', $id)->delete();
        db('exam_list')->where(['exams_id' => $id, 'status' => 4])->update(['status' => 3]);
        db('exams')->where('id', $id)->update(['status' => 3]);
        db('exam_paper_images')->where(['exams_id' => $id, 'status' => 4])->update(['status' => 3]);
        $this->success('操作成功！');
    }

    //单科统分
    public function setSubjectTotalScore()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //科目id
        if (!$id)
            $this->error('未知参数！');

        $return = Papers::subjectScore($id);
        if (!empty($return)) {
            foreach ($return as $ret) {
                db('exam_paper_student_list')->insertGetId($ret);
            }
        }
        db('exam_list')->where('id', $id)->update(['status' => 4]);
        $this->success('操作成功！');
    }

    //单科取消统分
    public function cancelSubjectTotalScore()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //科目id
        if (!$id)
            $this->error('未知参数！');

        db('exam_paper_student_list')->where('exams_list_id', $id)->delete();
        db('exam_list')->where('id', $id)->update(['status' => 3]);
        $this->success('操作成功！');
    }

    //一键发布
    public function setPublish()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id)
            $this->error('未知参数！');
        //判断考试是否完成统分
        //科目总数
        $examListNum = db('exam_list')->where(['exams_id' => $id])->count();
        //待统分科目总数
        $overTaskNum = db('exam_list')->where(['exams_id' => $id, 'status' => 4])->count();
        // if ($examListNum != $overTaskNum) $this->error('有未完成统分的科目，无法发布！');
        $ids = db('exam_list')->where(['exams_id' => $id, 'status' => 4])->column('id');
        db('exam_list')->where('id', 'in', $ids)->update(['status' => 5]);
        db('exams')->where('id', $id)->update(['status' => 5]);
        db('exam_paper_student')->where('exams_id', $id)->update(['status' => 1]);
        db('exam_paper_student_list')->where('exams_id', $id)->update(['status' => 1]);
        db('exam_paper_images')->where('exams_id', $id)->update(['status' => 5]);
        $this->success('操作成功！');
    }

    //取消发布
    public function cancelPublish()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id)
            $this->error('未知参数！');

        db('exam_list')->where(['exams_id' => $id, 'status' => 5])->update(['status' => 4]);
        db('exams')->where('id', $id)->update(['status' => 4]);
        db('exam_paper_student')->where('exams_id', $id)->update(['status' => 0]);
        db('exam_paper_student_list')->where('exams_id', $id)->update(['status' => 0]);
        db('exam_paper_images')->where(['exams_id' => $id, 'status' => 5])->update(['status' => 4]);
        $this->success('操作成功！');
    }

    //考试成绩总览
    public function sumResult()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //单科Id
        if (!$id)
            $this->error('未知参数！');
        $info = db('exam_list')->where('id', $id)->find();
        if (!$info)
            $this->error('未找到相关科目信息！');
        //学生数
        $studentNum = $info['studentnum'];
        //参加考试考生数
        $paperNum = db('exam_paper_student_list')->where(['exams_list_id' => $id])->count();
        //缺考人数
        $queNUm = bcsub($studentNum, $paperNum, 0) > 0 ? bcsub($studentNum, $paperNum, 0) : 0;
        //本科总得分
        $listScoreNum = db('exam_paper_student_list')->where(['exams_list_id' => $id])->sum('totalscore');
        //客观题总得分
        $kScoresNum = db('exam_paper_student_list')->where(['exams_list_id' => $id])->sum('kscoresum');
        //主题总得分
        $zScoresNum = db('exam_paper_student_list')->where(['exams_list_id' => $id])->sum('zscoresum');
        //本科平均分
        $avgNum = 0;
        //客观题平均分
        $kavgNum = 0;
        //主观题平均分
        $zavgNum = 0;
        if ($paperNum > 0) {
            //本科平均分
            $avgNum = getAverage($listScoreNum, $paperNum);
            //客观题平均分
            $kavgNum = getAverage($kScoresNum, $paperNum);
            //主观题平均分
            $zavgNum = getAverage($zScoresNum, $paperNum);
        }

        //最高
        $max = db('exam_paper_student_list')->where(['exams_list_id' => $id])->max('totalscore');
        //最低
        $min = db('exam_paper_student_list')->where(['exams_list_id' => $id])->min('totalscore');

        $data = [
            'studentNum' => $studentNum,
            'paperNum' => $paperNum,
            'queNUm' => $queNUm,
            'listScoreNum' => $listScoreNum,
            'kScoresNum' => $kScoresNum,
            'zScoresNum' => $zScoresNum,
            'avgNum' => $avgNum,
            'kavgNum' => $kavgNum,
            'zavgNum' => $zavgNum,
            'max' => $max,
            'min' => $min
        ];

        $this->success('考试成绩总览', $data);
    }

    //成绩列表
    public function gradeList()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //单科Id
        $school_id = $this->request->post('school_id'); //学校Id
        $class_id = $this->request->post('class_id'); //班级Id
        $keyword = $this->request->post('keyword'); //班级Id
        $page = $this->request->post('page'); //页码
        $pagesize = $this->request->post('pagesize'); //每页显示的数量
        if (!$id)
            $this->error('未知参数！');

        $list = db('exam_paper_student_list')
            ->where(['exams_list_id' => $id])
            ->where(function ($query) use ($school_id) {
                if ($school_id) {
                    $query->where('school_id', $school_id);
                }
            })
            ->where(function ($query) use ($class_id) {
                if ($class_id) {
                    $query->where('class_id', $class_id);
                }
            })
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->where('student_name|exam_number|stu_number', 'like', '%' . $keyword . '%');
                }
            })->paginate($pagesize, false)->each(function ($item, $index) {
            $item['paperImage'] = db('exam_paper_images')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id']])->field('image')->select();
            $item['className'] = db('school_class')->where('id', $item['class_id'])->value('name');
            $blocklist = db('exam_teacher_make_log')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id']])->field('block_id,teacher_id,distinguish')->select();
            foreach ($blocklist as &$value) {
                $value['blockname'] = db('exam_paper_block')->where('id', $value['block_id'])->value('name');
                $value['distinguish'] = $value['distinguish'] ? json_decode($value['distinguish'], true) : '';
            }
            $item['blocklist'] = $blocklist;
            return $item;
        });

        $this->success('成绩列表', $list);
    }

    //成绩列表
    public function gradeListNew()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //单科Id
        $school_id = $this->request->post('school_id'); //学校Id
        $class_id = $this->request->post('class_id'); //班级Id
        $keyword = $this->request->post('keyword'); //关键词
        $page = $this->request->post('page'); //页码
        $pagesize = $this->request->post('pagesize'); //每页显示的数量
        if (!$id)
            $this->error('未知参数！');
        $exams_id = db('exam_list')->where(['id'=> $id])->value('exams_id');
        $class_ids = db('exams')->where(['id'=> $exams_id])->value('class_ids');

        $list = db('students')->where(function ($query) use ($school_id) {
            if ($school_id) {
                $query->where('school_id', $school_id);
            }
        })
        ->where(function ($query) use ($class_id,$class_ids) {
            if ($class_id) {
                $query->where('class_id', $class_id);
            }else if ($class_ids){
                $query->where('class_id','in', $class_ids);
            }
        })
        ->where(function ($query) use ($keyword) {
            if ($keyword) {
                $query->where('name|exam_number|stu_number', 'like', '%' . $keyword . '%');
            }
        })->paginate($pagesize, false)->each(function ($item, $index) {
            $item['paperImage'] = db('exam_paper_images')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id']])->field('image')->select();
            $item['className'] = db('school_class')->where('id', $item['class_id'])->value('name');
            $blocklist = db('exam_teacher_make_log')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id']])->field('block_id,teacher_id,distinguish')->select();
            foreach ($blocklist as &$value) {
                $value['blockname'] = db('exam_paper_block')->where('id', $value['block_id'])->value('name');
                $value['distinguish'] = $value['distinguish'] ? json_decode($value['distinguish'], true) : '';
            }
            $item['blocklist'] = $blocklist;
            return $item;
        });


        $list = db('exam_paper_student_list')
            ->where(['exams_list_id' => $id])
            ->where(function ($query) use ($school_id) {
                if ($school_id) {
                    $query->where('school_id', $school_id);
                }
            })
            ->where(function ($query) use ($class_id) {
                if ($class_id) {
                    $query->where('class_id', $class_id);
                }
            })
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->where('student_name|exam_number|stu_number', 'like', '%' . $keyword . '%');
                }
            })->paginate($pagesize, false)->each(function ($item, $index) {
            $item['paperImage'] = db('exam_paper_images')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id']])->field('image')->select();
            $item['className'] = db('school_class')->where('id', $item['class_id'])->value('name');
            $blocklist = db('exam_teacher_make_log')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id']])->field('block_id,teacher_id,distinguish')->select();
            foreach ($blocklist as &$value) {
                $value['blockname'] = db('exam_paper_block')->where('id', $value['block_id'])->value('name');
                $value['distinguish'] = $value['distinguish'] ? json_decode($value['distinguish'], true) : '';
            }
            $item['blocklist'] = $blocklist;
            return $item;
        });

        $this->success('成绩列表', $list);
    }

    //成绩信息
    public function gradeInfo()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //成绩信息
        if (!$id)
            $this->error('未知参数！');
        $info = db('exam_paper_student_list')->where(['id' => $id])->find();
        if ($info) {
            $info['paperImage'] = db('exam_paper_images')->where(['exams_list_id' => $info['exams_list_id'], 'student_id' => $info['student_id']])->field('image')->select();
            $info['className'] = db('school_class')->where('id', $info['class_id'])->value('name');
        }
        $this->success('成绩信息', $info);
    }

    //修改成绩信息
    public function editGradeInfo()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //成绩信息
        $kscoresum = $this->request->post('kscoresum'); //客观题成绩
        $blocklist = $this->request->post('blocklist/a'); //主观题成绩
        if (!$id)
            $this->error('未知参数！');
        if (empty($blocklist))
            $this->error('参数格式错误！');
        $info = db('exam_paper_student_list')->where(['id' => $id])->find();
        if (!$info)
            $this->error('未找到科目相关信息，请重试！');
        $exams = db('exam_paper_student')->where(['exams_id' => $info['exams_id'], 'student_id' => $info['student_id']])->find();
        if (!$exams)
            $this->error('未找到考试相关信息，请重试！');
        $zscoresum = 0;
        foreach ($blocklist as $list) {
            foreach ($list['distinguish'] as $dis) {
                $zscoresum = bcadd($zscoresum, $dis['mark'], 2);
            }
        }
        //单科总分
        $totalscore = bcadd($kscoresum, $zscoresum, 2);
        //差值
        $chaNum = bcsub($totalscore, $info['totalscore'], 2);
        //考试总分
        $examtotalscore = bcadd($exams['totalscore'], $chaNum, 2);
        $result = false;
        Db::startTrans();
        try {
            foreach ($blocklist as $list) {
                db('exam_teacher_make_log')->where(['exams_list_id' => $info['exams_list_id'], 'student_id' => $info['student_id'], 'block_id' => $list['block_id']])->update([
                    'distinguish' => json_encode($list['distinguish'])
                ]);
            }
            //单科
            db('exam_paper_student_list')->where(['id' => $id])->update([
                'kscoresum' => $kscoresum,
                'zscoresum' => $zscoresum,
                'totalscore' => $totalscore
            ]);

            //考试
            db('exam_paper_student')->where(['exams_id' => $info['exams_id'], 'student_id' => $info['student_id']])->update([
                'totalscore' => $examtotalscore
            ]);

            $result = true;
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            if ($chaNum != 0) {
                $kaoshi = db('exams')->where(['id' => $info['exams_id']])->find();
                //班级信息
                if ($kaoshi['class_ids']) {
                    $classIds = explode(',', $kaoshi['class_ids']);
                } else {
                    $classIds = db('school_class')->where(['grade_id' => $kaoshi['grade_id']])->colums('id');
                }
                //排名
                $list = db('exam_paper_student_list')->where(['exams_list_id' => $info['exams_list_id']])->select();
                if ($list) {
                    //按学校分组
                    Papers::setRank($list, 'school_id', 'exam_paper_student_list', 'schoolrank');
                    $lgradeExamList = db('exam_paper_student_list')->where(['exams_list_id' => $info['exams_list_id'], 'grade_id' => $kaoshi['grade_id']])->select();
                    if ($lgradeExamList) {
                        //按年级
                        Papers::setRank($lgradeExamList, 'grade_id', 'exam_paper_student_list', 'graderank');
                    }
                    foreach ($classIds as $classid) {
                        $lclassExamList = db('exam_paper_student_list')->where(['exams_list_id' => $info['exams_list_id'], 'class_id' => $classid])->select();
                        if ($lclassExamList) {
                            //按班级
                            Papers::setRank($lclassExamList, 'class_id', 'exam_paper_student_list', 'classrank');
                        }

                    }
                }


                //排名
                $examList = db('exam_paper_student')->where(['exams_id' => $info['exams_id']])->select();
                if ($examList) {
                    //按学校分组
                    Papers::setRank($examList, 'school_id', 'exam_paper_student', 'schoolrank');
                    $gradeExamList = db('exam_paper_student')->where(['exams_id' => $info['exams_id'], 'grade_id' => $kaoshi['grade_id']])->select();
                    if ($gradeExamList) {
                        //按年级
                        Papers::setRank($gradeExamList, 'grade_id', 'exam_paper_student', 'graderank');
                    }
                    //按班级
                    foreach ($classIds as $classid) {
                        $classExamList = db('exam_paper_student')->where(['exams_id' => $info['exams_id'], 'class_id' => $classid])->select();
                        if ($classExamList) {
                            Papers::setRank($classExamList, 'class_id', 'exam_paper_student', 'classrank');
                        }

                    }
                }


            }
            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //修改成绩信息
    public function addGradeInfo()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id'); //科目id
        $class_id = $this->request->post('class_id'); //班级id
        $student_name = $this->request->post('student_name'); //姓名
        $exam_number = $this->request->post('exam_number'); //考号
        $kscoresum = $this->request->post('kscoresum'); //客观题成绩
        $zscoresum = $this->request->post('zscoresum'); //客观题成绩
        // $blocklist = $this->request->post('blocklist/a'); //主观题成绩
        if (!$exams_list_id || !$class_id || !$student_name || !$exam_number)
            $this->error('未知参数！');
        // if (empty($blocklist))
        //     $this->error('参数格式错误！');

        //根据考号查询学生信息
        $student = db('student')->where(['class_id' => $class_id, 'exam_number' => $exam_number])->find();
        if (!$student)
            $this->error('未查到相关学生信息，请先录入学生信息！');
        $info = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$info)
            $this->error('未找到科目相关信息，请重试！');
        $exams = db('exams')->where(['id' => $info['exams_id']])->where('find_in_set(:keywords,class_ids)', ['keywords' => $class_id])->find();
        if (!$exams)
            $this->error('未找到考试相关信息，请重试！');
        // $zscoresum = 0;
        // foreach ($blocklist as $list) {
        //     foreach ($list['distinguish'] as $dis) {
        //         $zscoresum = bcadd($zscoresum, $dis['mark'], 2);
        //     }
        // }
        //单科总分
        $totalscore = bcadd($kscoresum, $zscoresum, 2);
        $check = db('exam_paper_student_list')->where(['exams_list_id' => $info['id'], 'student_id' => $student['id']])->find();
        if ($check)
            $this->error('成绩已存在请勿重复添加！');
        $data = [
            'school_id' => $student['school_id'],
            'exams_id' => $info['exams_id'],
            'exams_list_id' => $info['id'],
            'student_id' => $student['id'],
            'grade_id' => $student['grade_id'],
            'class_id' => $class_id,
            'subject_id' => $info['subject_id'],
            'student_name' => $student_name,
            'exam_number' => $exam_number,
            'stu_number' => $student['stu_number'],
            'totalscore' => $totalscore,
            'zscoresum' => $zscoresum,
            'kscoresum' => $kscoresum,
            'status' => 1,
            'createtime' => time()
        ];

        $result = false;
        Db::startTrans();
        try {
            
            //单科
            $in = db('exam_paper_student_list')->insertGetId($data);
            if ($in) {
                //考试总分
                $examtotalscore = db('exam_paper_student_list')->where(['exams_id' => $info['exams_id'], 'student_id' => $student['id']])->sum('totalscore');
                //考试
                $exam_paper_student = db('exam_paper_student')->where(['exams_id' => $info['exams_id'], 'student_id' => $student['id']])->find();
                if ($exam_paper_student) {
                    db('exam_paper_student')->where(['id' => $exam_paper_student['id']])->update(['totalscore' => $examtotalscore]);
                } else {
                    unset($data['exams_list_id']);
                    unset($data['zscoresum']);
                    unset($data['kscoresum']);
                    $data['totalscore'] = $examtotalscore;
                    db('exam_paper_student')->insertGetId($data);
                }
                $result = true;
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result) {
            $kaoshi = db('exams')->where(['id' => $info['exams_id']])->find();
            //班级信息
            if ($kaoshi['class_ids']) {
                $classIds = explode(',', $kaoshi['class_ids']);
            } else {
                $classIds = db('school_class')->where(['grade_id' => $kaoshi['grade_id']])->colums('id');
            }
            $list = db('exam_paper_student_list')->where(['exams_list_id' => $info['id']])->select();
            if ($list) {
                //按学校分组
                Papers::setRank($list, 'school_id', 'exam_paper_student_list', 'schoolrank');
                $lgradeExamList = db('exam_paper_student_list')->where(['exams_list_id' => $info['id'], 'grade_id' => $kaoshi['grade_id']])->select();
                if ($lgradeExamList) {
                    //按年级
                    Papers::setRank($lgradeExamList, 'grade_id', 'exam_paper_student_list', 'graderank');
                }
                foreach ($classIds as $classid) {
                    $lclassExamList = db('exam_paper_student_list')->where(['exams_list_id' => $info['id'], 'class_id' => $classid])->select();
                    if ($lclassExamList) {
                        //按班级
                        Papers::setRank($lclassExamList, 'class_id', 'exam_paper_student_list', 'classrank');
                    }

                }
            }

            //排名
            $examList = db('exam_paper_student')->where(['exams_id' => $info['exams_id']])->select();
            if ($examList) {
                //按学校分组
                Papers::setRank($examList, 'school_id', 'exam_paper_student', 'schoolrank');
                $gradeExamList = db('exam_paper_student')->where(['exams_id' => $info['exams_id'], 'grade_id' => $kaoshi['grade_id']])->select();
                if ($gradeExamList) {
                    //按年级
                    Papers::setRank($gradeExamList, 'grade_id', 'exam_paper_student', 'graderank');
                }
                //按班级
                foreach ($classIds as $classid) {
                    $classExamList = db('exam_paper_student')->where(['exams_id' => $info['exams_id'], 'class_id' => $classid])->select();
                    if ($classExamList) {
                        Papers::setRank($classExamList, 'class_id', 'exam_paper_student', 'classrank');
                    }

                }
            }

            $this->success('操作成功！');
        } else {
            $this->error('操作失败！');
        }
    }

    //进度监控列表
    public function scheduleList()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $type = $this->request->post('type'); //1=按题块，2=按老师
        if (!$exams_list_id || !$type)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        $exams_id = $exams_list['exams_id'];
        switch ($type) {
            case '1':
                #按题块
                $blockList = db('exam_paper_block')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id])->select();
                foreach ($blockList as &$value) {
                    $value['params'] = json_decode($value['params'], true);
                    $value['type_text'] = $this->blockType[$value['type']];
                    $value['allot_type_text'] = $this->allotType[$value['allot_type']];
                    $value['staynum'] = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'page' => 1])->count();
                    $value['alreadynum'] = db('exam_teacher_make_log')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'block_id' => $value['id']])->group('student_id')->count();
                    //阅卷进度
                    if ($value['staynum']) {
                        $value['scheduleNum'] = round(($value['alreadynum'] / $value['staynum']) * 100, 2);
                        $value['scheduleNum'] > 100 ? $value['scheduleNum'] = 100 : $value['scheduleNum'];
                    } else {
                        $value['scheduleNum'] = 0;
                    }
                }
                break;
            case '2':
                #按老师
                $teacherArr = [];
                $list = db('exam_paper_block')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id])->field('teacher_ids')->select();
                foreach ($list as $key => $value) {
                    $teachere = explode(',', $value['teacher_ids']);
                    foreach ($teachere as $key => $val) {
                        $teacherArr[] = $val;
                    }
                }
                $blockList = [];
                foreach ($teacherArr as $tid) {
                    $blockLists = db('exam_paper_block')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id])->where('find_in_set(:keywords,teacher_ids)', ['keywords' => $tid])->select();
                    foreach ($blockLists as &$value) {
                        $value['teacherName'] = db('user')->where('id', $tid)->value('nickname');
                        $value['params'] = json_decode($value['params'], true);
                        $value['type_text'] = $this->blockType[$value['type']];
                        $value['allot_type_text'] = $this->allotType[$value['allot_type']];
                        $value['staynum'] = db('exam_paper_images')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'page' => 1])->count();
                        $value['alreadynum'] = db('exam_teacher_make_log')->where(['exams_id' => $exams_id, 'exams_list_id' => $exams_list_id, 'block_id' => $value['id'], 'block_id' => $value['id']])->group('student_id')->count();
                        //阅卷进度
                        if ($value['staynum']) {
                            $value['scheduleNum'] = round(($value['alreadynum'] / $value['staynum']) * 100, 2);
                        } else {
                            $value['scheduleNum'] = 0;
                        }
                        //总的题块
                        $blockCount = $value['staynum'];
                        $value['blockCount'] = $blockCount;
                        //已批阅
                        $blockLog = db('exam_teacher_make_log')->where(['teacher_id' => $tid, 'exams_list_id' => $exams_list_id, 'block_id' => $value['id']])->count();
                        $value['blockLog'] = $blockLog;
                    }
                    if (!empty($blockLists)) {
                        $blockList = array_merge($blockList, $blockLists);
                        // $blockList[] = $blockLists;
                    }
                }

                break;
        }

        $this->success('进度监控列表', $blockList);
    }

    //监控进度按题块详情
    public function scheduleDetail()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id');
        if (!$id)
            $this->error('未知参数！');
        $block = db('exam_paper_block')->where(['id' => $id])->find();
        if (!$block)
            $this->error('未找到相关信息！');
        if ($block) {
            $block['params'] = json_decode($block['params'], true);
            $block['type_text'] = $this->blockType[$block['type']];
            $block['allot_type_text'] = $this->allotType[$block['allot_type']];
            $block['status_text'] = $this->statusType[$block['status']];
            $block['staynum'] = db('exam_paper_images')->where(['exams_id' => $block['exams_id'], 'exams_list_id' => $block['exams_list_id'], 'page' => 1])->count();
            $block['alreadynum'] = db('exam_teacher_make_log')->where(['exams_id' => $block['exams_id'], 'exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id']])->group('student_id')->count();
            //阅卷进度
            if ($block['staynum'] > 0) {
                $block['scheduleNum'] = round(($block['alreadynum'] / $block['staynum']) * 100, 2);
            } else {
                $block['scheduleNum'] = 0;
            }
            $teacherIds = explode(',', $block['teacher_ids']);
            $teachList = db('user')->where('id', 'in', $teacherIds)->field('id,nickname')->select();
            foreach ($teachList as $key => &$teach) {
                //阅卷数量
                $talreadynum = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $id, 'teacher_id' => $teach['id']])->count();
                $teach['talreadynum'] = $talreadynum;
                if ($block['staynum'] > 0) {
                    $teach['scheduleNum'] = round(($talreadynum / $block['staynum']) * 100, 2);
                } else {
                    $teach['scheduleNum'] = 0;
                }
            }
            //待阅数量
            $daiyueNum = bcsub($block['staynum'], $block['alreadynum'], 0);
            $block['daiyueNum'] = $daiyueNum;
            $block['teachList'] = $teachList;
        }

        $this->success('监控进度按题块详情', $block);
    }

    //质量监控题块列表
    public function monitorList()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exam = db('exam_list')->where('id', $exams_list_id)->find();
        if (!$exam)
            $this->error('未找到相关信息！');
        //该科目主观题总分
        $zscoreTotal = db('exam_paper_block')->where(['exams_list_id' => $exams_list_id])->sum('score');
        //客观题考试总得分
        $zexamScoreTotal = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id])->sum('bscore');
        //参考人数
        $paperCount = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'page' => 1])->count();
        //平均分
        $averageNum = 0;
        if ($paperCount > 0) {
            //平均分
            $averageNum = getAverage($zexamScoreTotal, $paperCount);
        }

        $blockList = db('exam_paper_block')->where(['exams_list_id' => $exams_list_id])->select();
        foreach ($blockList as $key => &$value) {
            $value['params'] = json_decode($value['params'], true);
            $value['type_text'] = $this->blockType[$value['type']];
            $value['allot_type_text'] = $this->allotType[$value['allot_type']];
            $value['status_text'] = $this->statusType[$value['status']];
            //题块总得分
            $blockScoreTotal = db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'block_id' => $value['id']])->sum('bscore');
            //题块平均分
            $baverageNum = 0;
            if ($paperCount > 0) {
                //平均分
                $baverageNum = getAverage($blockScoreTotal, $paperCount);
            }
            $blockList[$key]['baverageNum'] = $baverageNum;
        }

        $data = [
            'zscoreTotal' => $zscoreTotal,
            'averageNum' => $averageNum,
            'blockList' => $blockList
        ];
        $this->success('质量监控题块列表', $data);
    }

    //质量监控按学生列表
    public function monitorStudentList()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $school_id = $this->request->post('school_id'); //学校Id
        $class_id = $this->request->post('class_id'); //班级Id
        $keyword = $this->request->post('keyword'); //关键词
        $page = $this->request->post('page'); //页码
        $pagesize = $this->request->post('pagesize'); //每页显示的数量
        if (!$exams_list_id)
            $this->error('未知参数！');

        $list = db('exam_teacher_make_log')
            ->where(['exams_list_id' => $exams_list_id])
            ->where(function ($query) use ($school_id) {
                if ($school_id) {
                    $query->where('school_id', $school_id);
                }
            })
            ->where(function ($query) use ($class_id) {
                if ($class_id) {
                    $query->where('class_id', $class_id);
                }
            })
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->where('student_name|exam_number|stu_number', 'like', '%' . $keyword . '%');
                }
            })->group('student_id')->paginate($pagesize, false)->each(function ($item, $index) {
            $item['paperImage'] = db('exam_paper_images')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id']])->field('image')->select();
            $item['className'] = db('school_class')->where('id', $item['class_id'])->value('name');
            $item['distinguish'] = json_decode($item['distinguish'], true);
            //客观题得分
            $item['kscore'] = db('exam_paper_images')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id'], 'page' => 1])->value('scoresum');
            $item['bscore'] = db('exam_teacher_make_log')->where(['exams_list_id' => $item['exams_list_id'], 'student_id' => $item['student_id']])->sum('bscore');
            //总分
            $item['totalscore'] = bcadd($item['bscore'], $item['kscore'], 2);
            //题块数
            $blockNum = db('exam_paper_block')->where(['exams_list_id' => $item['exams_list_id']])->count();
            $item['blockNum'] = $blockNum;
            //已评卷数
            $makeNum = db('exam_teacher_make_log')->where(['exams_list_id' => $item['exams_list_id']])->field('block_id')->group('block_id')->count();
            $item['makeNum'] = $makeNum;
            //阅卷进度
            $item['scheduleNum'] = 0;
            if ($blockNum > 0) {
                $item['scheduleNum'] = round(($makeNum / $blockNum) * 100, 2) . '%';
            }
            return $item;
        });
        $this->success('质量监控按学生列表', $list);
    }

    //题块评分老师列表
    public function makeTeacherList()
    {
        $block_id = $this->request->post('block_id'); //题块Id
        if (!$block_id)
            $this->error('未知参数！');
        $block = db('exam_paper_block')->where(['id' => $block_id])->find();
        if (!$block)
            $this->error('未找到相关题块信息！');
        $teacherList = db('user')->where('id', 'in', $block['teacher_ids'])->field('id,nickname')->select();
        $this->success('题块评分老师列表', $teacherList);
    }

    //阅卷质量
    public function makeQuality()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $block_id = $this->request->post('block_id'); //题块Id
        if (!$block_id)
            $this->error('未知参数！');
        $block = db('exam_paper_block')->where(['id' => $block_id])->find();
        if (!$block)
            $this->error('未找到相关题块信息！');
        $teacherList = db('user')->where('id', 'in', $block['teacher_ids'])->field('id,nickname')->select();
        foreach ($teacherList as $key => &$teacher) {
            //阅卷量
            $makeNum = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->count();
            //阅卷总得分
            $makeScore = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->sum('bscore');
            //平均分
            $makeAverageScore = 0;
            if ($makeNum > 0) {
                $makeAverageScore = getAverage($makeScore, $makeNum);
            }
            //打分数组
            $bscoreArray = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->column('bscore');
            //标准差
            $standardScore = 0;
            if (!empty($bscoreArray)) {
                $standardScore = getStandardDeviation($bscoreArray);
            }
            //第一份试卷时间
            $firstTime = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->order('id asc')->value('createtime');
            //当前最后一份试卷试卷
            $endTime = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->order('id desc')->value('createtime');
            //总耗时
            $useTime = strtotime($endTime) - strtotime($firstTime);
            //平均用时
            $averageTime = 0;
            if ($makeNum > 0) {
                $averageTime = getAverage($useTime, $makeNum);
            }
            $teacher['makeNum'] = $makeNum; //阅卷量
            $teacher['makeAverageScore'] = $makeAverageScore; //平均分
            $teacher['averageTime'] = $averageTime; //平均用时
            $teacher['standardScore'] = $standardScore; //标准差
        }

        $this->success('阅卷质量', $teacherList);
    }

    //给分分布
    public function giveScore()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $block_id = $this->request->post('block_id'); //题块Id
        $teacher_id = $this->request->post('teacher_id'); //评分老师Id
        if (!$block_id)
            $this->error('未知参数！');
        $block = db('exam_paper_block')->where(['id' => $block_id])->find();
        if (!$block)
            $this->error('未找到相关题块信息！');
        $data = [];
        if (!$teacher_id) {
            $teacherList = db('user')->where('id', 'in', $block['teacher_ids'])->field('id,nickname')->select();
            foreach ($teacherList as $key => $teacher) {
                $data[$key]['name'] = $teacher['nickname'];
                $data[$key]['data'] = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->column('bscore');
            }
        } else {
            $teacher = db('user')->where('id', $teacher_id)->field('id,nickname')->find();
            if ($teacher) {
                $data[] = [
                    'name' => $teacher['nickname'],
                    'data' => db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->column('bscore')
                ];
            }
        }
        $this->success('给分分布', $data);
    }

    //平均分
    public function averageList()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $block_id = $this->request->post('block_id'); //题块Id
        $teacher_id = $this->request->post('teacher_id'); //评分老师Id
        if (!$block_id)
            $this->error('未知参数！');
        $block = db('exam_paper_block')->where(['id' => $block_id])->find();
        if (!$block)
            $this->error('未找到相关题块信息！');
        $data = [];
        if (!$teacher_id) {
            $teacherList = db('user')->where('id', 'in', $block['teacher_ids'])->field('id,nickname')->select();
            foreach ($teacherList as $key => $teacher) {
                $data[$key]['name'] = $teacher['nickname'];
                //阅卷量
                $makeNum = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->count();
                //阅卷总得分
                $makeScore = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->sum('bscore');
                //平均分
                $makeAverageScore = 0;
                if ($makeNum > 0) {
                    $makeAverageScore = getAverage($makeScore, $makeNum);
                }
                $data[$key]['value'] = $makeAverageScore;
            }
        } else {
            $teacher = db('user')->where('id', $teacher_id)->field('id,nickname')->find();
            if ($teacher) {
                //阅卷量
                $makeNum = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->count();
                //阅卷总得分
                $makeScore = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->sum('bscore');
                //平均分
                $makeAverageScore = 0;
                if ($makeNum > 0) {
                    $makeAverageScore = getAverage($makeScore, $makeNum);
                }
                $data[] = [
                    'name' => $teacher['nickname'],
                    'value' => $makeAverageScore
                ];
            }
        }
        $this->success('平均分', $data);
    }
    //标准差
    public function standardList()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $block_id = $this->request->post('block_id'); //题块Id
        $teacher_id = $this->request->post('teacher_id'); //评分老师Id
        if (!$block_id)
            $this->error('未知参数！');
        $block = db('exam_paper_block')->where(['id' => $block_id])->find();
        if (!$block)
            $this->error('未找到相关题块信息！');
        $data = [];
        if (!$teacher_id) {
            $teacherList = db('user')->where('id', 'in', $block['teacher_ids'])->field('id,nickname')->select();
            foreach ($teacherList as $key => $teacher) {
                $data[$key]['name'] = $teacher['nickname'];
                //打分数组
                $bscoreArray = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->column('bscore');
                //标准差
                $standardScore = 0;
                if (!empty($bscoreArray)) {
                    $standardScore = getStandardDeviation($bscoreArray);
                }
                $data[$key]['value'] = $standardScore;
            }
        } else {
            $teacher = db('user')->where('id', $teacher_id)->field('id,nickname')->find();
            if ($teacher) {
                //打分数组
                $bscoreArray = db('exam_teacher_make_log')->where(['exams_list_id' => $block['exams_list_id'], 'block_id' => $block['id'], 'teacher_id' => $teacher['id']])->column('bscore');
                //标准差
                $standardScore = 0;
                if (!empty($bscoreArray)) {
                    $standardScore = getStandardDeviation($bscoreArray);
                }
                $data[] = [
                    'name' => $teacher['nickname'],
                    'value' => $standardScore
                ];
            }
        }
        $this->success('标准差', $data);
    }


    //答题卡旋转图片
    public function imageRotate()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //Id
        $angle = $this->request->post('angle'); //选装角度
        $type = $this->request->post('type'); //类型 1=答题卡，2=模板
        if (!$id || !in_array($type, [1, 2]))
            $this->error('未知参数！');

        switch ($type) {
            case '1':
                $model = 'exam_paper_images';
                $field = 'image';
                break;
            case '2':
                $model = 'exam_images';
                $field = 'zimage';
                break;
        }
        $paper = db($model)->where(['id' => $id])->find();
        if (!$paper)
            $this->error('未找到相关信息！');
        if (!$angle)
            $this->success('操作成功！', $paper[$field]);
        $fileimage = pathinfo($paper[$field]);
        $imagePath = explode('.com', $fileimage['dirname']);
        $image = $this->basepath . $imagePath[1] . '/' . $fileimage['basename'];
        $mairk = $imagePath[1];
        $outputFile = $mairk . '/' . md5(date('YmdHis', time()) . Random::uuid()) . '.png';
        Image::rotate($image, $outputFile, $angle);
        db($model)->where(['id' => $id])->update([$field => cdnurl($outputFile, true)]);
        $this->success('操作成功！', cdnurl($outputFile, true));
    }

    //答题卡倾斜图片
    public function imageShear()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $id = $this->request->post('id'); //Id
        $angle = $this->request->post('angle'); //选装角度
        $type = $this->request->post('type'); //类型 1=答题卡，2=模板
        if (!$id || !in_array($type, [1, 2]))
            $this->error('未知参数！');

        switch ($type) {
            case '1':
                $model = 'exam_paper_images';
                $field = 'image';
                break;
            case '2':
                $model = 'exam_images';
                $field = 'zimage';
                break;
        }
        $paper = db($model)->where(['id' => $id])->find();
        if (!$paper)
            $this->error('未找到相关信息！');
        if (!$angle)
            $this->success('操作成功！', $paper[$field]);
        $fileimage = pathinfo($paper[$field]);
        $imagePath = explode('.com', $fileimage['dirname']);
        $image = $this->basepath . $imagePath[1] . '/' . $fileimage['basename'];
        $mairk = $imagePath[1];
        $outputFile = $mairk . '/' . md5(date('YmdHis', time()) . Random::uuid()) . '.png';
        Image::shear($image, $outputFile, $angle);
        db($model)->where(['id' => $id])->update([$field => cdnurl($outputFile, true)]);
        $this->success('操作成功！', cdnurl($outputFile, true));
    }

    //打回重阅
    public function again()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id'); //科目id
        $block_id = $this->request->post('block_id'); //题块id
        if (!$exams_list_id || !$block_id)
            $this->error('未知参数！');
        db('exam_teacher_make_log')->where(['exams_list_id' => $exams_list_id, 'block_id' => $block_id])->delete();
        db('task')->where(['exams_list_id' => $exams_list_id, 'block_id' => $block_id])->update(['status' => 1]);
        $this->success('操作成功！');
    }

    //异常数量
    public function abnormalNum()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id'); //科目id
        if (!$exams_list_id)
            $this->error('未知参数！');
        //定位异常
        $locationNum = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'status' => -3])->count();
        //考号异常
        $examNum = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'status' => -1])->count();
        //考号重复
        $examRepeatNum = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'status' => -4])->count();

        $data = [
            'locationNum' => $locationNum,
            'examNum' => $examNum,
            'examRepeatNum' => $examRepeatNum,
        ];
        $this->success('异常数量', $data);
    }



    //下载学生成绩
    public function stuGradeExcel()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误！');
        $id = $this->request->post('id'); //单科Id
        $school_id = $this->request->post('school_id'); //学校Id
        $class_id = $this->request->post('class_id'); //班级Id
        $keyword = $this->request->post('keyword'); //班级Id
        $page = $this->request->post('page'); //页码
        $pagesize = $this->request->post('pagesize'); //每页显示的数量
        if (!$id)
            $this->error('未知参数！');

        $data = db('exam_paper_student_list')
            ->where(['exams_list_id' => $id])
            ->where(function ($query) use ($school_id) {
                if ($school_id) {
                    $query->where('school_id', $school_id);
                }
            })
            ->where(function ($query) use ($class_id) {
                if ($class_id) {
                    $query->where('class_id', $class_id);
                }
            })
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->where('student_name|exam_number|stu_number', 'like', '%' . $keyword . '%');
                }
            })->select();

        //->page($page,$pagesize)
        // 处理数据
        foreach ($data as &$v) {
            $v['className'] = db('school_class')->where('id', $v['class_id'])->value('name');
        }
        unset($v);
        // 加载sheet
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Sheet1');

        // 处理标题
        $title = [
            'className' => '班级',
            'student_name' => '姓名',
            'exam_number' => '考号',
            'totalscore' => '总得分',
            'kscoresum' => '客观题得分',
            'zscoresum' => '主观题得分'
        ];
        $keys = 1;
        foreach ($title as $key => $value) {
            $sheet->setCellValueByColumnAndRow($keys, 1, $value);
            $sheet->getDefaultColumnDimension()->setWidth(15);
            $keys++;
        }
        // 处理标题下内容
        // 从第二行开始
        $row = 2;
        foreach ($data as $item) {
            $column = 1;
            foreach ($title as $key => $value) {
                $sheet->setCellValueByColumnAndRow($column, $row, $item[$key]);
                $column++;
            }
            $row++;
        }

        // 文件下载
        $filename = '学生成绩信息' . date('YmdHis') . '.xlsx';
        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        $xlsData = ob_get_contents();
        ob_end_clean();
        $this->success('学生成绩信息', ['filename' => $filename, 'file' => 'data:application/vnd.ms-excel;base64,' . base64_encode($xlsData)]);
    }

    //获取未扫描学生列表
    public function getNoSaoStudentLiset()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $page = $this->request->post('page'); //页码
        $pagesize = $this->request->post('pagesize'); //每页显示的数量
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        $exams = db('exams')->where(['id' => $exams_list['exams_id']])->find();
        if (!$exams)
            $this->error('未找到相关试卷信息！');
        $schoolIds = explode(',', $exams['school_ids']);
        $classIds = $exams['class_ids'] ? explode(',', $exams['class_ids']) : '';
        $studentIds = [];
        $paperList = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->field('student_id')->select();
        foreach ($paperList as $key => $paper) {
            if ($paper['student_id']) {
                $studentIds[] = $paper['student_id'];
            }
        }
        $studentIds = array_unique($studentIds);
        $list = db('student')->where('school_id', 'in', $schoolIds)->where(['grade_id' => $exams['grade_id']])->where('id', 'not in', $studentIds)->where(function ($query) use ($classIds) {
            if ($classIds) {
                $query->where('class_id', 'in', $classIds);
            }
        })
            ->field('id,name,exam_number,class_name')->paginate($pagesize, false);
        $this->success('未扫描学生列表', $list);
    }

    //获取扫描学生列表
    public function getSaoStudentLiset()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误');
        $exams_list_id = $this->request->post('exams_list_id');
        $page = $this->request->post('page'); //页码
        $pagesize = $this->request->post('pagesize'); //每页显示的数量
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        $exams = db('exams')->where(['id' => $exams_list['exams_id']])->find();
        if (!$exams)
            $this->error('未找到相关试卷信息！');
        $schoolIds = explode(',', $exams['school_ids']);
        $classIds = $exams['class_ids'] ? explode(',', $exams['class_ids']) : '';
        $studentIds = [];
        $paperList = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->field('student_id ')->select();
        foreach ($paperList as $key => $paper) {
            if ($paper['student_id']) {
                $studentIds[] = $paper['student_id'];
            }
        }
        $studentIds = array_unique($studentIds);
        //->where('school_id', 'in', $schoolIds)->where(['grade_id' => $exams['grade_id']])
        $list = db('student')->where('id', 'in', $studentIds)
            // ->where(function ($query) use ($classIds) {
            //     if ($classIds) {
            //         $query->where('class_id', 'in', $classIds);
            //     }
            // })
            ->field('id,name,exam_number,class_name')->paginate($pagesize, false)->each(function ($item, $index) use ($exams_list_id) {
                $item['paperImage'] = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id, 'student_id' => $item['id']])->field('image')->select();
                return $item;
            });
        $this->success('已扫描学生列表', $list);
    }


    //下载未扫描学生
    public function noSaoStudentLExcel()
    {
        if (!$this->request->isPost())
            $this->error('请求方式错误！');
        $exams_list_id = $this->request->post('exams_list_id');
        if (!$exams_list_id)
            $this->error('未知参数！');
        $exams_list = db('exam_list')->where(['id' => $exams_list_id])->find();
        if (!$exams_list)
            $this->error('未找到相关试卷信息！');
        $exams = db('exams')->where(['id' => $exams_list['exams_id']])->find();
        if (!$exams)
            $this->error('未找到相关试卷信息！');
        $schoolIds = explode(',', $exams['school_ids']);
        $classIds = $exams['class_ids'] ? explode(',', $exams['class_ids']) : '';
        $studentIds = [];
        $paperList = db('exam_paper_images')->where(['exams_list_id' => $exams_list_id])->field('student_id')->select();
        foreach ($paperList as $key => $paper) {
            if ($paper['student_id']) {
                $studentIds[] = $paper['student_id'];
            }
        }
        $studentIds = array_unique($studentIds);
        $data = db('student')->where('school_id', 'in', $schoolIds)->where(['grade_id' => $exams['grade_id']])->where('id', 'not in', $studentIds)->where(function ($query) use ($classIds) {
            if ($classIds) {
                $query->where('class_id', 'in', $classIds);
            }
        })
            ->field('id,name,exam_number,class_name')->select();
        // 处理数据

        // 加载sheet
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setTitle('Sheet1');

        // 处理标题
        $title = [
            'class_name' => '班级',
            'name' => '姓名',
            'exam_number' => '考号'
        ];
        $keys = 1;
        foreach ($title as $key => $value) {
            $sheet->setCellValueByColumnAndRow($keys, 1, $value);
            $sheet->getDefaultColumnDimension()->setWidth(15);
            $keys++;
        }
        // 处理标题下内容
        // 从第二行开始
        $row = 2;
        foreach ($data as $item) {
            $column = 1;
            foreach ($title as $key => $value) {
                $sheet->setCellValueByColumnAndRow($column, $row, $item[$key]);
                $column++;
            }
            $row++;
        }

        // 文件下载
        $filename = '未扫描学生信息' . date('YmdHis') . '.xlsx';
        // Redirect output to a client’s web browser (Xlsx)
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        $xlsData = ob_get_contents();
        ob_end_clean();
        $this->success('未扫描学生信息', ['filename' => $filename, 'file' => 'data:application/vnd.ms-excel;base64,' . base64_encode($xlsData)]);
    }

    //学生导入
    public function importStudent()
    {
        $model = new Student();
        $file = $this->request->post('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }

        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];

        try {
            $tags = ['复读生', '借读生', '艺术生', '体育生', '学生'];
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            $school_id = $this->school_id;
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);

                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {

                        $row['school_id'] = $school_id;
                        $row['salt'] = Random::alnum();
                        $row['password'] = $this->auth->getEncryptPassword('123456', $row['salt']);
                        $row['create_time'] = time();
                        $row[$fieldArr[$k]] = $v;

                        if ($fieldArr[$k] == 'grade_id') {
                            $row[$fieldArr[$k]] = db('school_grade')->where(['school_id' => $school_id, 'name' => $v])->value('id') ?? 0;
                            $row['grade_name'] = $v;
                            $row['stage_id'] = db('school_grade')->where(['school_id' => $school_id, 'name' => $v])->value('stage_id') ?? 0;
                            $row['stage_data'] = db('school_stage')->where(['id' => $row['stage_id']])->value('name') ?? '';
                        }
                        if ($fieldArr[$k] == 'class_id') {
                            $row[$fieldArr[$k]] = db('school_class')->where(['school_id' => $school_id, 'type' => 'XZ', 'name' => $v])->value('id');
                            $row['class_name'] = $v;
                        }
                        if ($fieldArr[$k] == 'tag') {
                            $row[$fieldArr[$k]] = in_array($v, $tags) ? array_search($v, $tags) + 1 : '';
                        }
                        if ($fieldArr[$k] == 'elective_ids') {
                            $row[$fieldArr[$k]] = implode(',', db('school_class')->whereIn('name', $v)->where(['school_id' => $row['school_id']])->column('id'));
                        }
                        if ($fieldArr[$k] == 'foreign_subject_ids') {
                            $row[$fieldArr[$k]] = implode(',', db('subject')->whereIn('name', $v)->where(['school_id' => $row['school_id'], 'type' => 2])->column('id'));
                        }

                        if ($fieldArr[$k] == 'select_exam_id') {
                            $row[$fieldArr[$k]] = db('select_exam')->where(['school_id' => $school_id, 'name' => $v])->value('id');
                        }
                    }
                }

                if ($row) {
                    unset($row['id']);
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }
        $errorMessage = [];
        try {
            foreach ($insert as $key => $value) {
                $info = db('student')->where(['school_id' => $school_id, 'stu_number' => $value['stu_number']])->find();
                if ($info) {
                    array_push($errorMessage, $value['stu_number'] . '该学号已存在，请确认输入是否正确！');
                    continue;
                } else {
                    $in = db('student')->insert($value);
                    if ($in) {
                        if ($value['chinese_class']) {
                            //语文教学班
                            //获取学科id
                            $subject_id = db('subject')->where('name', '语文')->value('id');
                            $this->checkClass($value['grade_id'], $value['chinese_class'], $subject_id);
                        }

                        if ($value['maths_class']) {
                            //数学教学班
                            //获取学科id
                            $subject_id = db('subject')->where('name', '数学')->value('id');
                            $this->checkClass($value['grade_id'], $value['maths_class'], $subject_id);
                        }

                        if ($value['english_class']) {
                            //英语教学班
                            //获取学科id
                            $subject_id = db('subject')->where('name', '英语')->value('id');
                            $this->checkClass($value['grade_id'], $value['english_class'], $subject_id);
                        }

                        if ($value['physics_class']) {
                            //物理教学班
                            //获取学科id
                            $subject_id = db('subject')->where('name', '物理')->value('id');
                            $this->checkClass($value['grade_id'], $value['physics_class'], $subject_id);
                        }

                        if ($value['chemistry_class']) {
                            //化学教学班
                            //获取学科id
                            $subject_id = db('subject')->where('name', '化学')->value('id');
                            $this->checkClass($value['grade_id'], $value['chemistry_class'], $subject_id);
                        }

                        if ($value['organism_class']) {
                            //生物教学班
                            //获取学科id
                            $subject_id = db('subject')->where('name', '生物')->value('id');
                            $this->checkClass($value['grade_id'], $value['organism_class'], $subject_id);
                        }

                        if ($value['politics_class']) {
                            //政治教学班
                            //获取学科id
                            $subject_id = db('subject')->where('name', '政治')->value('id');
                            $this->checkClass($value['grade_id'], $value['politics_class'], $subject_id);
                        }

                        if ($value['history_class']) {
                            //历史教学班
                            //获取学科id
                            $subject_id = db('subject')->where('name', '历史')->value('id');
                            $this->checkClass($value['grade_id'], $value['history_class'], $subject_id);
                        }

                        if ($value['geography_class']) {
                            //地理教学班
                            //获取学科id
                            $subject_id = db('subject')->where('name', '地理')->value('id');
                            $this->checkClass($value['grade_id'], $value['geography_class'], $subject_id);
                        }

                        if ($value['other_class']) {
                            //其他教学班
                            $this->checkClass($value['grade_id'], $value['other_class']);
                        }
                    }
                }
            }
            if ($errorMessage) {
                throw new Exception(implode(',', $errorMessage));
            }
            // $model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            }
            ;
            $this->error('错误信息！', $msg, 300);
        } catch (Exception $e) {
            $this->error('错误信息！', $e->getMessage(), 300);
        }

        $this->success();
    }
}
